The problem is MainActivity starts with a setContentView with a layout.xml. We can add buttons or anything to the layout and code in in the MainActivity class but when I try to code the buttons of another layout in the same Activity the app forces stop . Whats wrong ?
Ok I found out that is because of the context.
When you try to change other activity you have to use layoutinflater. Example below
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, null);
To work with widgets inside it like buttons or anything .
Button b = mylayout.findViewById(R.id.button);
b.setText("Successfully changed");
Now you can use myLayout as your changed layout.
Please sent me your Activities
What the text of problem ?
You may write next code to go to another activity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),nameActivity.class));
}
});
Where button is name of your button
See that you xml-file doesnt have any mistakes
You are getting a crash because you are trying to access the layout when it is not inflated. In other words, you must call setContentView() on an Activity, or inflater.inflate() on a Fragment to instantiate the view and make the elements accessible for manipulation. So if you want to add buttons to another Activity, you would need to call its onCreate() and setContentView() before you can add buttons to it.
EDIT: In response to comments...
In order to access/manipulate/modify elements in a layout at runtime, they must first be instantiated, which happens when the view is inflated. So to add a button to an Activity at runtime, you would do it in the onCreate() method after calling setContentView() like this:
Keep in mind this is the onCreate() of your SECOND activity...not your main Activity. So your main activity would start this Activity, then the button would get created during the setup of the second Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_second_activity;
Button button = new Button(this);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.layout_in_your_second_activity);
relativeLayout.addView(button);
}
If you are using a Fragment to display your UI, you can't access your UI elements until you have inflated your layout, which happens in the onCreateView() method. So you would do something like this in your Fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.container_layout_that_holds_button);
//You would get your context from an onAttach() Override
Button button = new Button(context);
button.setText("Your New Button");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NEW BUTTON", "I just clicked my new button!");
}
});
relativeLayout.addView(button);
return view;
}
You're likely getting a NullPointerException when you try to manipulate your layouts before they are created. Keep in mind that even if you have an XML file with layouts specified within, the actual objects for those elements won't be created until the system decides it needs them, which happens when you actually try to display the view.
Related
public class Home extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home,null);
}}
This is the whole code for fragment tab 1..
I have a program with two TabFragments , and I want to declare an image button and button intent in fragment tab 1 and 2, but I can't do it , and the findviewbyid did not work..
What can I do to declare buttons intent ??
To handle button clicks (and view clicks in general) View.OnClickListener interface is used. All you have to do is override its onClick method and assign it to a view by calling setOnClickListener().
You can also find a thorough tutorial here.
UPD: Your method should look like this:
public View onCreateView(.....) {
// assign inflated view to a variable
View v = inflater.inflate(R.layout_services, null);
// set your listener
v.findViewById(R.id.imageButton).setOnClickListener(.....);
// return the view in the end
return v;
}
The problem is that you're instantly returning the inflated view and the code below wouldn't run at all, this is why there's that error.
UPD2: Now the problem is that startActivity method is receiving Context as a first parameter, so you should pass your activity there by calling getActivity() (instead of passing Services.this). You can read more here.
UPD3: You don't seem to understand what your code does. Your findViewById call is useless because it's not getting assigned to a variable, and your setOnClickListener is getting applied to the entire fragment view. Here's what that part should look like:
ImageButton button = (ImageButton) v.findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Activity activity = getActivity();
Intent intent = new Intent(activity, Admin.class);
activity.startActivity(intent);
}
});
I'd recommend to learn how all those methods work (at least have a look at the reference, to begin with: here and here) before trying to actually write an application. Good luck with it.
I created a class that extends ActionBarActivity and displays a custom XML. That class is extended by almost all my activities.
I want to access an element of that custom XML from one of my activities. Let's say I want to change the background of item2 when I'm in Activity2.
In my activity's onCreate method, after setContentView, I tried:
View cView = getLayoutInflater().inflate(R.layout.custom_menu, null);
ImageButton rewards_link = (ImageButton) cView.findViewById(R.id.rewards_link);
rewards_link.setVisibility(View.GONE); // For test purpose
Even if the button id seems correct, the changes doesn't apply. Any ideas ?
If you are setting the custom view via getActionBar().setCustomView(R.layout.custom_menu); (or getSupportActionBar() for v21 of AppCompat), then you can access those views by using findViewById() directly as the view is part of your view hierarchy just like views added via setContentView():
ImageButton rewards_link = (ImageButton) findViewById(R.id.rewards_link);
rewards_link.setVisibility(View.GONE); // For test purpose
Use #getCustomView
View view =getSupportActionBar().getCustomView(); ImageButton imageButton =
(ImageButton)view.findViewById(R.id.action_bar_back); imageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v){
// Your code here ...
}
});
I'm completely new to Android and am trying to add a simple button to my view, but my view is completely blank. Here is my setup:
EDIT: I have now changed my code to write this programmatically since I'm used to that with iOS.
I'm now getting the following error:
Error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setOrientation(int)' on a null object reference
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Create main view
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
}
}
You need to setContentView which takes a View or a layout resource id.
Also, you can only call findViewById if you provide a layout resource id, and call setContentView with it. Alternatively, you could inflate it and call view.findViewById on the resulting inflated view.
Here's your code with some changes that should hopefully fix your new issue:
public class MainActivity extends Activity {
LinearLayout linearLayout;
public Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// Create main view
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// Create button
myButton = new Button(this);
myButton.setText("Fire Call");
// Add button to view
linearLayout.addView(myButton);
setContentView(linearLayout);
}
}
I cannot pinpoint the error but maybe you can.
Try checking after every line you type and see if the button appears. Also check if the problem is with button only or does it extend to other layouts as well.
Just type and see what happens.
Follow it up with dimensions.
Don not forget to save after each step. Usually all such problems can be solved by detailed debugging.
If none of the layout appears, try and restart the software.
You didn't callsetContentView(R.layout.activity_main) , in your code there, you commented it out, so your layout wasnt inflated so you got a blank white screen. Uncomment that line and you will be fine.
I'm working on one demo project in that I had create one XML file containing some views like ImageView, EditText. I'm loading this XML file on FrameLayout at runtime. At one point I want to remove all that views and again want to display them, I used removeView() method on button click but it does not work for me,,Please tell me the right way to do it..
public class Demo extends Fragment implements OnClickListener, OnTouchListener{
//Declaration of framelayout
FrameLayout f;
//Declaration of imageview
ImageView imageview;
View view, framelayoutview;
File file;
EditText etcardname, EditTextUserName,EditTextUsesrMobNumber,EditTextUsesrEmailID,EditTextUsesrAddress;
TextView dialogtesting;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_modify_card ,container, false);
framelayoutview = inflater.inflate(R.layout.frame_layout_data ,container, false);
captureImageInitialization();
Initialize();
return view;
}
// Initialization of all views components
private void Initialize() {
f=(FrameLayout)view.findViewById(R.id.framelayout);
Button btneditcardreset=(Button)view.findViewById(R.id.buttonresetcard);
btneditcardreset.setOnClickListener(this);
Bundle bundle = this.getArguments();
int myInt;
myInt = bundle.getInt("position");
imageview=(ImageView)framelayoutview.findViewById(R.id.imageViewicon);
EditTextUserName=(EditText)framelayoutview.findViewById(R.id.modifycardeditTextusername);
EditTextUsesrMobNumber=(EditText)framelayoutview.findViewById(R.id.editTextmobilesnumber);
EditTextUsesrEmailID=(EditText)framelayoutview.findViewById(R.id.editTextemailid);
EditTextUsesrAddress=(EditText)framelayoutview.findViewById(R.id.editTextaddress);
imageview.setOnTouchListener(this);
EditTextUserName.setOnTouchListener(this);
EditTextUsesrMobNumber.setOnTouchListener(this);
EditTextUsesrEmailID.setOnTouchListener(this);
EditTextUsesrAddress.setOnTouchListener(this);
f.addView(framelayoutview);
}
#Override
public void onClick(View v){
if(v.getId()==R.id.buttonresetcard){
if(framelayoutview.getParent()!=null){
f.removeAllViews();
}
f.addView(framelayoutview);
}
}
Sorry to all I forgot to tell that I provided OnTouchListener so that I can move the views anywhere in Layout. So when I press reset button all Views should get move back to their original location means where they were at on first load..
you can use
imageview.setVisibility(View.GONE);
And
imageview.setVisibility(View.VISIBLE);
on particular event
If you had added your views dynamically to your FrameLayout then you can remove them.
Otherwise, if you showing your views from XML which are exist inside the frameLayout XML then you can't remove them but you can hide them from showing by setting setVisibility(View.GONE) or setVisibility(View.INVISIBLE).
Try this-
#Override
public void onClick(View v){
if(v.getId()==R.id.buttonresetcard){
if(framelayoutview.getParent()!=null){
f.setVisibility(View.GONE);
}
f.addView(framelayoutview);
}
}
i have an activity that displays two buttons , on click of call button i want to show another activity as shown in image.
Please help .How to achieve this
One way to do it is to have a custom layout which you add to each activity with a viewgroup as such:
private View view;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup parent = (ViewGroup) findViewById(R.id.linearLayout1);
view = LayoutInflater.from(getBaseContext()).inflate(R.layout.custom_layout,
null);
parent.addView(view);
Then you just need to implement your listeners and whatnot further down :)
You need to create xml file of these two buttons and add that new xml into old one by using Layout Inflator. for e.g
1) your new xml
LayoutInflator buttons = LayoutInflater.from(getBaseContext()).inflate(R.layout.buttons,
currentxml, false);
2) your old xml parent referenced through id -->
RelativeLayout relativeLayout = (RelatveLayout) findViewById(R.id.oldxml);
3) now add..
relativeLayout.addView(buttons);
You can Use Pop up By Adding this in your function. Popuser is a xml file which you want to inflate.
public void popupshow(){
try{
LayoutInflater inflater=(LayoutInflater)SRSDMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Display display=getWindowManager().getDefaultDisplay();
int width=display.getWidth()/2;
int height=display.getHeight()/2;
View pop=inflater.inflate(R.layout.popupuser,null,false);
pop.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
height=pop.getMeasuredHeight();
width=pop.getMeasuredWidth()+50;
pu=new PopupWindow(pop,width,height,true);
pu.showAtLocation(findViewById(R.id.ll3),Gravity.CENTER,1,1);
Button btn=(Button)pu.getContentView().findViewById(R.id.button);
btn.getBackground().setColorFilter(new LightingColorFilter(0xFF505450,0xFF101010));
btn.setTextColor(Color.WHITE);
btn.setTypeface(null,Typeface.BOLD);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//anything you want to do
pu.dismiss();
}
});
}
catch(Exception ex){
//Catch The Exception
}
}
}