adding onclicklistener to linearlayout in fragment - android

I have a fragment which I am using as a navigational menu between my activities.
Each of the icons is in a seperate linearlayout with its own ID. I'm trying to implement an onclick listener in the fragment for each linearlayout so that when it is clicked the appropriate activity is opened and the background of the linear layout as well as the image in the imageview are changed to signify the click. However when I click on the linearlayout nothing happens. I already set the clickable attribute to true so that is not the issue. This is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
LinearLayout betslayout = (LinearLayout) this.getView().findViewById(R.id.betnowlayout);
betslayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout layout = (LinearLayout) v;
layout.setBackgroundResource(R.drawable.selected);
ImageView image = (ImageView) layout.findViewById(R.id.betnowimageview);
image.setImageResource(R.drawable.footballsell);
LinearLayout parent = (LinearLayout) v.getParent();
LinearLayout mybetslayout = (LinearLayout) parent.findViewById(R.id.viewbetslayout);
LinearLayout rankingslayout = (LinearLayout) parent.findViewById(R.id.rankingslayout);
LinearLayout coinfrenzylayout = (LinearLayout) parent.findViewById(R.id.coinfrenzylayout);
LinearLayout shoplayout = (LinearLayout) parent.findViewById(R.id.shoplayout);
mybetslayout.setBackgroundResource(R.drawable.notselected);
rankingslayout.setBackgroundResource(R.drawable.notselected);
coinfrenzylayout.setBackgroundResource(R.drawable.notselected);
shoplayout.setBackgroundResource(R.drawable.notselected);
ImageView mybetsimage = (ImageView) mybetslayout.findViewById(R.id.betnowimageview);
ImageView rankingsimage = (ImageView) rankingslayout.findViewById(R.id.rankingsimageview);
ImageView coinfrenzyimage = (ImageView) coinfrenzylayout.findViewById(R.id.coinfrenzyimageview);
ImageView shopimage = (ImageView) shoplayout.findViewById(R.id.shopimageview);
mybetsimage.setImageResource(R.drawable.chipp);
rankingsimage.setImageResource(R.drawable.medal);
coinfrenzyimage.setImageResource(R.drawable.clover);
shopimage.setImageResource(R.drawable.moneybag);
Intent i = new Intent(getActivity(),AllGameslistActivity.class);
startActivity(i);
getActivity().finish();
}
});
}

First Off All You Should Create Custom Buttons. See this.
and set onClickListener for the Icons.

The problem was in this line of code
return inflater.inflate(R.layout.fragment_menu, container, false);
It should instead be : return myfragment;
This is the proper way to do this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myfragment = inflater.inflate(R.layout.fragment_menu, container, false);
// TODO: Rename method, update argument and hook method into UI event
LinearLayout betslayout = (LinearLayout) myfragment.findViewById(R.id.betnowlayout);
betslayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("isitworkign", "yesyes");
LinearLayout layout = (LinearLayout) v;
layout.setBackgroundResource(R.drawable.selected);
ImageView image = (ImageView) layout.findViewById(R.id.betnowimageview);
image.setImageResource(R.drawable.footballsell);
LinearLayout parent = (LinearLayout) v.getParent();
LinearLayout mybetslayout = (LinearLayout) parent.findViewById(R.id.viewbetslayout);
LinearLayout rankingslayout = (LinearLayout) parent.findViewById(R.id.rankingslayout);
LinearLayout coinfrenzylayout = (LinearLayout) parent.findViewById(R.id.coinfrenzylayout);
LinearLayout shoplayout = (LinearLayout) parent.findViewById(R.id.shoplayout);
mybetslayout.setBackgroundResource(R.drawable.notselected);
rankingslayout.setBackgroundResource(R.drawable.notselected);
coinfrenzylayout.setBackgroundResource(R.drawable.notselected);
shoplayout.setBackgroundResource(R.drawable.notselected);
ImageView mybetsimage = (ImageView) parent.findViewById(R.id.viewbetsimageview);
ImageView rankingsimage = (ImageView) parent.findViewById(R.id.rankingsimageview);
ImageView coinfrenzyimage = (ImageView) parent.findViewById(R.id.coinfrenzyimageview);
ImageView shopimage = (ImageView) parent.findViewById(R.id.shopimageview);
mybetsimage.setImageResource(R.drawable.chipp);
rankingsimage.setImageResource(R.drawable.medal);
coinfrenzyimage.setImageResource(R.drawable.clover);
shopimage.setImageResource(R.drawable.moneybag);
Intent i = new Intent(getActivity(), AllGameslistActivity.class);
startActivity(i);
getActivity().finish();
}
});
return myfragment;
}

Related

How to get views from fragments in onClick

I have an activity with a String array and a Drawable array. I create fragments using a for loop in the onCreate according to the length of the arrays and use the String array to fill TextViews in the fragments.
I made the fragments clickable and added onClick in the fragment class.
I want to get the text from the fragment the user clicks, but when I click it only gets the text from the first fragment. How can I read the textviews in the different fragments.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int layoutId = getArguments().getInt("layout");
View rootView = inflater.inflate(layoutId, container, false);
TextView fragmentText = (TextView) rootView.findViewById(R.id.fragTextView);
fragmentText.setText(getArguments().getString("fragText"));
ImageView fragmentImage = (ImageView) rootView.findViewById(R.id.fragImageView);
fragmentImage.setImageResource(getArguments().getInt("pic"));
rootView.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
String s = ((TextView)v.getRootView().findViewById(R.id.fragTextView)).getText().toString();
Intent intent = new Intent(v.getContext(), LevelActivity.class);
intent.putExtra("exerciseId", s);
startActivity(intent);
}
Thanks

Null Pointer Exception when setting new text to text view

I am trying to run an AndroidApp on my phone. I am able to show my welcome fragment, moreover I can trigger the log-message. Unfortunately I am getting a null pointer exception if I want to change the text value from 'welcome' to 'Neuer Text'. What went wrong? I am quite new to android development.
public class WelcomeFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
Button button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
return view;
}
#Override
public void onClick(View v) {
//Log.d("JobaApp", "Logtext"); // see LogCat
TextView text1 = (TextView) v.findViewById(R.id.welcome_text);
text1.setText("NeuerText");
}
}
In the onClick(), v is the view item that was clicked, e.g. the button, not the view that is inflated in onCreateView().
You should use getView():
public class WelcomeFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
Button button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
return view;
}
#Override
public void onClick(View v) {
//Log.d("JobaApp", "Logtext"); // see LogCat
switch (v.getId) {
case R.id.button1:
TextView text1 = (TextView) getView().findViewById(R.id.welcome_text);
text1.setText("NeuerText");
break;
}
}
}
Also, if you don't want that action taking place for every button you may want to consider using a switch statement in your onClick().
You cant get the TextView from the button's onClick passed parameter ("View v"), since this is the actual button's view.
You should do something like:
public class WelcomeFragment extends Fragment implements OnClickListener {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_welcome, container, false);
Button button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
return view;
}
#Override
public void onClick(View v) {
//Log.d("JobaApp", "Logtext"); // see LogCat
TextView text1 = (TextView) view.findViewById(R.id.welcome_text);
text1.setText("NewerText"); //Also fixed typo
}
}
In OnClick(View v) , v is the button that you are clicking on. The TextView does not belong to Button, it belongs to R.layout.fragment_welcome. So you find and initialize the TextView inside onCreateView() of the fragment, and then use it inside onClick();
Some what like this:
public class WelcomeFragment extends Fragment implements OnClickListener {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
Button button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
tv = (TextView) v.findViewById(R.id.welcome_text);
return view;
}
#Override
public void onClick(View v) {
//Log.d("JobaApp", "Logtext"); // see LogCat
tv.setText("NeuerText");
}
}

setting the background colour from program rather than from xml for fragments

I need some help in setting the background colour using code for my current fragment. The fragment is created on selecting a particular tab.
Below is my main activity code
public class TabActionBarActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the text and background colour
setTheme(R.style.MyTheme);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String label6 = getResources().getString(R.string.label6);
tab = actionBar.newTab();
tab.setText(label6);
TabListener<Tab6Fragment> tl6 = new TabListener<Tab6Fragment>(this,
label6, Tab6Fragment.class);
tab.setTabListener(tl6);
actionBar.addTab(tab);
String label7 = getResources().getString(R.string.label7);
tab = actionBar.newTab();
tab.setText(label7);
TabListener<Tab7Fragment> tl7 = new TabListener<Tab7Fragment>(this,
label7, Tab7Fragment.class);
tab.setTabListener(tl7);
actionBar.addTab(tab);
}
Now the code for the Tab7Fragment class looks like this
public class Tab7Fragment extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ScrollView sv = new ScrollView(this.getActivity());
LinearLayout ll = new LinearLayout(this.getActivity());
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this.getActivity());
tv.setText("Dynamic layouts ftw!");
ll.addView(tv);
EditText et = new EditText(this.getActivity());
et.setText("weeeeeeeeeee~!");
ll.addView(et);
Button b = new Button(this.getActivity());
b.setText("I don't do anything, but I was added dynamically. :)");
ll.addView(b);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(this.getActivity());
cb.setText("I'm dynamic!");
ll.addView(cb);
}
return this.getView();
}
}
Now how can i set the view for this fragment?
this.getActivity().setContentView(sv);
I know the above method is incorrect. But i need to set the content view with the scrollview layout. and another question is how do i set the background colour for this view?(using setBackgroundColor()?
Try this code in your onCreateView():
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
Then dont forget to return the view that you just inflated to the android runtime.
Remove return this.getView(); and add return view;
To set background color :
sv.setBackgroundColor(getRessources().getColors(R.color.yourcolor));
To inflate layout into a fragment, you need to return a View from onCreateView :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.your layout, container, false);
}

Fragmentation Layout inflater issue

hello guys..
i want to add two layout in my fragmentation .one layout already inflated after that second layout inflate on first layout button click...well i tried to remove first layout on button click of first layout button and inflate second layout but my button click does not response any type of reaction..please help me
public static LinearLayout mLL_MyNotes,mLin_myNotes,mLL_UploadNotes;
public static ViewFlipper mVF_MyNotes,mViewUploadMyNotes;
public static View mViewMyNotes;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
if(mContent.equalsIgnoreCase("My Notes")){
mViewMyNotes = inflater.inflate(R.layout.activity_myspace_mynotes_list, container, false);
mLin_myNotes=(LinearLayout)mViewMyNotes.findViewById(R.id.mainLin_MyNotes);
mVF_MyNotes = (ViewFlipper) mViewMyNotes.findViewById(R.id.vf_MySpace_MyNotes);
mbtn_Upload_MyNotes = (Button) mViewMyNotes.findViewById(R.id.btnUpload_MySpace_MyNotes);
mWV_MyNotes = (WebView) mViewMyNotes.findViewById(R.id.wv_MySpace_MyNotes);
mLV_MyNotes = (ListView) mViewMyNotes.findViewById(R.id.lv_MySpace_MyNotes);
mLV_MyNotes.setAdapter(new MySpace_MyNotesAdapter(getActivity(),R.layout.activity_myspace_mynotes_listitem));
mbtn_Upload_MyNotes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater Newinflater = (LayoutInflater) getActivity().
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewUploadMyNotes==Newinflater.inflate(R.layout.activity_myspace_mynotes_uploades,null);
mLL_UploadNotes = (LinearLayout) mViewUploadMyNotes.findViewById(R.id.llUpload_MyNotes);
((ViewGroup) mLin_myNotes.getParent()).removeView(mViewUploadMyNotes);
mLin_myNotes.addView(mViewUploadMyNotes);
}
});
return mViewMyNotes;

Inflate a layout with ImageButton inside Fragment programmatically

I am new on android development, and i was currently creating an application using tabhost and a TabActivity to switch between different activities. This application was working fine, but I recently discover that TabActivity are deprecated and I should use fragment instead.
So, I follow this great tutorial explaining how to do so :
http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
Most of it works fine, but there is my problem some of my old activities which are now fragments were inflating ImageButton using this kind of methods :
private void displayLevelButtons() {
LayoutInflater lf = getLayoutInflater();
btns = lf.inflate(R.layout.mallmapactivity_level_buttons, null, false);
mBtnLevelDown = (ImageButton) btns.findViewById(R.id.btn_level_down);
mBtnLevelUp = (ImageButton) btns.findViewById(R.id.btn_level_up);
mBtnLevelDown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
levelDown();
updateLevelButtons();
}
});
mBtnLevelUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
levelUp();
updateLevelButtons();
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL | Gravity.RIGHT;
addContentView(btns,params);
}
In order to be able to compile this method inside a fragment, I changed:
LayoutInflater lf = getLayoutInflater();
to
LayoutInflater lf = getActivity().getLayoutInflater();
and
addContentView(btns,params);
to
getActivity().addContentView(btns,params);
But using my method displayLevelButtons() like this make my buttons appears in the right bottom of my general view, not in the right bottom of my fragment.
I also tried to specify a root when inflating my layout with image buttons, my all fragment class looking like this :
public class MyFragment extends Fragment {
private View btns;
private ImageButton mBtnLevelUp;
private ImageButton mBtnLevelDown;
private ViewGroup myViewGroup;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
myViewGroup = container;
v = inflater.inflate(R.layout.mallmaptile, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//Do some stuff and then :
displayLevelButtons();
}
private void displayLevelButtons() {
LayoutInflater lf = getActivity().getLayoutInflater();
btns = lf.inflate(R.layout.mallmapactivity_level_buttons, myViewGroup, false);
mBtnLevelDown = (ImageButton) btns.findViewById(R.id.btn_level_down);
mBtnLevelUp = (ImageButton) btns.findViewById(R.id.btn_level_up);
mBtnLevelDown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
levelDown();
updateLevelButtons();
}
});
mBtnLevelUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
levelUp();
updateLevelButtons();
}
});
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL | Gravity.RIGHT;
getActivity().addContentView(btns,params);
}
Doing so my buttons are still display in the bottom of my general view not in the bottom of my fragment, and if I try to change the attachToRoot boolean value to true :
btns = lf.inflate(R.layout.mallmapactivity_level_buttons, myViewGroup, true);
I get the error : java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
I am sure, I missed something important but I don't what. Any suggestions would be really appreciated.
Thanks in advance,
If you are facing problem in inflating layout then you can use following code:
View headerView = View.inflate(this, R.layout.layout_name, null);
this will give you complete parent layout then you can use that layout to fetch whatever view you want or you can get layout param and then set layout param to any views (In your case button I think).
I had same problem and find my answer in this link:
problem with inflater
you can do it without any dependency
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.view_with_merge_tag, this);

Categories

Resources