Programmatic Toolbar - java

In my Android assignment we have to create a simple App using only Java and not design view. I want to add icons and text to the toolbar. I can get it to work using design view but I cannot get it to work using Java.
Please advice me if my idea is right. For example to add a button to the toolbar, I create a
android.widget.Button button = new android.widget.Button()
and then add the button to the Toolbar.
My onCreate() function is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
relative_layout = new RelativeLayout(this);
relative_layout.setBackgroundColor(Color.WHITE);
Toolbar tool_bar = new Toolbar(this);
tool_bar.setTitle("Hello");
tool_bar.setBackgroundColor(Color.RED); // actual one I read from R.color.xyz
tool_bar.setTitleTextColor(Color.WHITE);
tool_bar.setId(1);
// tool_bar.setNavigationIcon(R.drawable.ic_launcher_foreground);
tool_bar.setPopupTheme(R.style.Theme_AppCompat_Dialog);
this.setVisible(true);
this.setSupportActionBar(tool_bar);
RelativeLayout.LayoutParams toolbar_layout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
toolbar_layout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
toolbar_layout.addRule(RelativeLayout.CENTER_HORIZONTAL);
Button button = new Button(this);
button.setBackgroundColor(Color.GREEN);
button.setText("Button");
button.setId(2);
RelativeLayout.LayoutParams button_layout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
button_layout.addRule(RelativeLayout.CENTER_HORIZONTAL);
button_layout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// button_layout.setMargins(400, 0, 0, 0);
tool_bar.addView(button, button_layout);
relative_layout.addView(tool_bar, toolbar_layout);
this.setContentView(relative_layout);
}
1) I would like to confirm is this is correct way of doing this?
2) I cannot move the button to the right of the screen as shown in the picture, although I used
RelativeLayout.ALIGN_PARENT_RIGHT
How can we set the alignment to the right?

Your Toolbar will look like this after adding this code :
Use this code to crate your toolbar activity.xml Code :
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Activity.java Code :
Toolbar toolbarTop;
Call setToolbar() inside from your onCreate()
private void setToolbar() {
toolbarTop = (Toolbar) findViewById(R.id.toolbarAdjustScan);
setSupportActionBar(toolbarTop);
TextView search = (TextView)toolbarTop.findViewById(R.id.searchAdjustBtn);
TextView titleToolbar = (TextView)toolbarTop.findViewById(R.id.titleToolbar);
titleToolbar.setText("TakeInventory");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(0);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), TakeInventoryResult.class);
// Bundle args = new Bundle();
// args.putSerializable("ARRAYLIST",(Serializable)inList);
// intent.putExtra("BUNDLE",args);
startActivity(intent);
finish();
}
});
}

The toolbar is just a ViewGroup. So just as you add views to any ViewGroup programmatically, do the same treatment for the toolbar.
Button bt = new Button(this);
bt.setText("Button");
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.FILL_PARENT);
params.gravity = Gravity.RIGHT;
button.setLayoutParams(params);
toolbar.addView(bt);
Happy to help :)

Related

How to create a scroll list of custom relative layouts not stacking upon each other in Android Studio?

I want to create a scroll view list which would show "boxes" or more accurately custom made layouts (I'm using a custom class that extends a RelativeLayout - basically shows different pieces of information, some are static like places' working hours and some change dynamically and will be pulled from a server).
Though I encountered a problem - I (for the sake of seeing if my solution works) created 5 boxes and added them to the scroll view list but it seems like they are stacked upon each other. What's the proper way to make them appear one under another without manually tweaking their position coordinates? I was using addView() for that purpose but it doesn't work as intended for me or I use it poorly. If you know the answer, please briefly describe how this should be done.
Thanks in advance!
EDIT, here goes the code:
public class RestaurantBox extends RelativeLayout {
RestaurantBox (Context context){
super(context);
this.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
TextView restaurantName = new TextView(context);
restaurantName.setText("Test Restaurant");
RelativeLayout.LayoutParams restNameParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
this.addView(restaurantName, restNameParams);
restaurantName.setTypeface(null, Typeface.BOLD);
TextView freeSpots = new TextView(context);
freeSpots.setText("15/20");
RelativeLayout.LayoutParams freeSpotParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
freeSpotParams.topMargin = restNameParams.bottomMargin + 50;
this.addView(freeSpots, freeSpotParams);
TextView book = new TextView(this.getContext());
RelativeLayout.LayoutParams bookParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
book.setText("Book");
bookParams.setMargins(0,freeSpotParams.bottomMargin + 100,0,0);
this.addView(book, bookParams);
}
}
public class BrowseRestaurants extends AppCompatActivity {
int restaurantCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_restaurants);
Intent intent = getIntent();
String login = intent.getStringExtra("LOGIN");
TextView text = (TextView) findViewById(R.id.txtWelcomeUser);
text.setText("Welcome, " + login);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relLayoutRestaurants);
RestaurantBox initRBox = new RestaurantBox(this);
initRBox.setTop(0);
initRBox.setBottom(300);
relativeLayout.addView(initRBox);
for(int i=1;i<5;i++){
final View view = relativeLayout.getChildAt(i-1);
RestaurantBox restaurantBox = new RestaurantBox(this);
restaurantBox.setTop(view.getBottom() + 50);
restaurantBox.setBottom(restaurantBox.getTop() + 300);
relativeLayout.addView(restaurantBox);
}
}
}
<!-- activity_browse_restaurants.xml-->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical"
tools:context="com.konrad.rezerwacje1.BrowseRestaurants">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewRestaurants"
android:layout_below="#+id/txtWelcomeUser"
android:layout_alignParentStart="true">
<RelativeLayout
android:id="#+id/relLayoutRestaurants"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="65dp"
android:orientation="vertical">
</RelativeLayout>
</ScrollView>
<TextView
android:id="#+id/txtLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Logout"
android:textColor="#android:color/holo_red_dark"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/txtWelcomeUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#android:color/holo_blue_dark"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp" />
</RelativeLayout
>
you are adding view in RelativeLayout so view stacking on each other so change it to LinearLayout in activity_browse_restaurants.xml
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewRestaurants"
android:layout_below="#+id/txtWelcomeUser"
android:layout_alignParentStart="true">
<LinearLayout
android:id="#+id/relLayoutRestaurants"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="65dp"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
now make changes according to in BrowseRestaurants.class
replace
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relLayoutRestaurants);
with
LinearLayout relativeLayout = (LinearLayout) findViewById(R.id.relLayoutRestaurants);
else will be fine if you want to change variable name its up to u, let me know if any problem

Android Adding Buttons to Toolbar Programmatically

I am trying to create a toolbar programmatically and add left and right bar buttons without using XML.
But the button is not getting aligned to right.
Toolbar TopTulBarVar = new Toolbar(this);
TopTulBarVar.setId(View.generateViewId());
TopTulBarVar.setBackgroundColor(Color.parseColor("#DDDDDD"));
TopTulBarVar.setTitle("Ttl Txt");
TopTulBarVar.setSubtitle("Dtl Txt");
Button NamBarBtnVar = new Button(this);
NamBarBtnVar.setText("Select");
NamBarBtnVar.setBackgroundColor(Color.GREEN);
LinearLayout.LayoutParams NamBarBtnRulVar = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
NamBarBtnRulVar.gravity = Gravity.RIGHT;
TopTulBarVar.addView(NamBarBtnVar, NamBarBtnRulVar);
Also tried
RelativeLayout.LayoutParams RloRulVar = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RloRulVar.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
I am getting as below image
But need like
In Activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar t = (Toolbar) findViewById(R.id.tool);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//left side button
Button b = new Button(this);
Toolbar.LayoutParams l1=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l1.gravity = Gravity.START;
b.setLayoutParams(l1);
b.setText("left");
t.addView(b);
//center Textview
TextView text=new TextView(this);
text.setText("Text:1");
Toolbar.LayoutParams l2 = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l2.gravity = Gravity.CENTER;
text.setLayoutParams(l2);
t.addView(text);
//Right side button
Button b1=new Button(this);
b1.setText("Right");
Toolbar.LayoutParams l3=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
l3.gravity=Gravity.END;
b1.setLayoutParams(l3);
t.addView(b1);
}
Toolbar XML code
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:id="#+id/tool"
app:contentInsetLeft="0dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
OUTPUT
For anyone struggling with this nowadays: please make sure to use androidx.appcompat.widget.Toolbar.LayoutParams while adding view programmatically as for me just typing Toolbar.LayoutParams were accidentally resolved to android.widget.Toolbar.LayoutParams by Android Studio. I spent some time trying to figure out why gravity is not changed: no exception occures if set wrond layoutParams before adding a view to the toolbar. I have androidx.appcompat.widget.Toolbar in my layout.
for me I added one switch button in Toolbar and it does work :
<Toolbar
android:id="#+id/toolbar"
style="#style/Toolbar"
android:visibility="visible"
android:background="#color/white">
<Switch
android:id="#+id/btn_accessible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:layout_weight="1"
android:visibility="visible"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textColor="#color/white"
android:textSize="12sp"
android:thumb="#drawable/custom_switch_thumb"
android:track="#drawable/custom_switch_track"
/>
</Toolbar>
and in activity i just set onClick listener

Why won't my TextView add to RelativeLayout?

I am trying to add my textView to my app programmatically, but it doesn't appear when I run it.I put a button in the XML to test the relativeLayout and it appears fine, but the textView doesn't so I'm putting down to code? my code is below. Thanks in advance!
#Override
public void onResponse(String response) {
StringX = response;
Log.e("RESPONSE", response);
TextView valueTV = new TextView(getBaseContext());
valueTV.setText("Hello!");
valueTV.setTextSize(20);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
valueTV.setLayoutParams(params);
valueTV.setTextColor(Color.argb(1, 0, 95, 0));
valueTV.setId(0);
scrollerF.addView(valueTV);
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.garethpower92.tourlink_ireland.coupons">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="70dp"
android:background="#FFFFFF"
android:id="#+id/scrollerMain"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:fillViewport="false">
<RelativeLayout
android:id="#+id/rlX"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</RelativeLayout>
</ScrollView>
<TextView
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Discounts"
android:id="#+id/textView"
android:textColor="#FFFFFF"
android:textSize="40sp"
android:background="#009500"
android:textAlignment="center"
android:paddingTop="10sp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Below code works for me,
In your activity onCreate method add this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTextv = new TextView(getApplicationContext());
mTextv.setText("This is Text....!!");
mTextv.setGravity(Gravity.CENTER_VERTICAL);
linearLayout = (LinearLayout) findViewById(R.id.lLayout);
mTextv.setTextSize(20);
mTextv.setTypeface(Typeface.MONOSPACE);
mTextv.setTextColor(Color.parseColor("#454045"));
linearLayout.addView(mTextv);
}
Linear layout is the parent layout of TextView you'll add dynamically, so ad textview as child view in linearLayout object.
try this.
TextView valueTV = new TextView(scrollerF.getContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
valueTV.setLayoutParams(params.addRule(RelativeLayout.CENTER_IN_PARENT));
valueTV.setText("Hello!");
valueTV.setTextSize(20);
scrollerF.addView(valueTV);
scrollerF.invalidate();

how to set text to text view based on the selection of item in dialogfragment and value of text in main activity, is it possible?

Here I am trying to set text to a textview in my activity.
The text is set to the text view based on the text of the text view in my activity and the selected item in the custom dialog fragment.
The dialog fragment consists of recycler view and a button.when item is selected from the fragment and text of textview of my activity, and with both cases settext to the textview. I tried different code but I not getting how to achieve it anyone give me solution for it. is there a way to get it.
by using value of text and selected item, adding my math and condition to it. settext to the textview. I am beginner to coding can any one help me please I'm trying from 5 days to achieve it. please help me thanks in advance
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="YOUR DAILY TARGET"
android:layout_gravity="center"
android:id="#+id/textView7"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_gravity="center"
android:id="#+id/res"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select a glass"
android:layout_marginLeft="10dp"
android:id="#+id/textView6"
android:layout_gravity="center" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="70dp"
android:layout_height="70dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:background="#drawable/circle"
android:gravity="center"
android:id="#+id/glasses"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="31dp"
android:layout_marginEnd="31dp"
android:layout_marginBottom="121dp" />
</RelativeLayout>
</LinearLayout>
MainActivity:
public class MainActivity extends AppCompatActivity {
private Listen selectedListen;
protected void setDataFromMyDialog(Listen listen) {
this.selectedListen = listen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, Page.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
TextView textView = (TextView)findViewById(R.id.res);
Intent r = getIntent();
double res = r.getDoubleExtra("res", 0);
textView.setText(+res + "L"); // with this text value
double ram = Double.parseDouble(textView.getText().toString());
TextView gls = (TextView) findViewById(R.id.glasses);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DiaFragment df = new DiaFragment();
df.show(MainActivity.this.getSupportFragmentManager(), "Frag");
}
});
}
with the text of textview above and selected item in my dialog fragment by using both the values the set text of TextView glasses.is it possible to get like this
DiaFrag:
public class DiaFragment extends DialogFragment {
ListAdapter listAdapter;
public DiaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
setCancelable(false);
Button ok = (Button) v.findViewById(R.id.submit);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.list);
listAdapter = new ListAdapter(getContext(),getData());
recyclerView.setAdapter(listAdapter);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setDataFromMyDialog(listAdapter.getSelectedData());
dismiss();
}
});
return v;
}
public static List<Listen> getData()
{
List<Listen> data = new ArrayList<>();
int[] images = {R.drawable.bottle,R.drawable.lotion,R.drawable.soap,R.drawable.soda,R.drawable.sodaa};
String[] texts = {"250ml","300ml","500ml","750ml","1ltr"};
for (int i=0;i<texts.length && i<images.length;i++){
Listen current = new Listen();
current.img = images[i];
current.text= texts[i];
data.add(current);
}
return data;
}
}

Android: made a text in RelativeLayout and can't change text in activity?

<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="#string/text"
android:textColor="#F0F8FF"
android:textSize="50sp"
android:textStyle="bold" />
This is declaration of the text field in activity_main.xml.
And the activity:
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(napis);
Program crashes when I call setText() in onReasume() and it doesn't do anything when I call setText() in onCreate().
Whole xml file as requested:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/zajebiste1" />
<Chronometer
android:textColor="#F0F8FF"
android:id="#+id/chronometer1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="46dp"
android:gravity="center"
android:textSize="40sp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="#string/text"
android:textColor="#F0F8FF"
android:textSize="50sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
Activity:
text = (TextView) findViewById(R.id.textView1);
text.setText("Your Text");
Can't show more, cause something doesn't work... xf
onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.textView1);
napis="Witaj!";
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//,........
text = (TextView) findViewById(R.id.textView1);
text.setText("Your Text");
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
onReasume():
#Override
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
First of all, what is up with
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.activity_main); ??
Can you try doing
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_main, this);
TextView text = (TextView) layout.findViewById(R.id.textView1);
text.setText(napis);
setContentView(layout);
set the contentView only once, towards the end of the method..
Try this, then post logcat if it doesn't work

Categories