change Imagebutton background after refreshing fragment - android

im still new in android developement.
I want to refresh my fragment and getting new imageButton background in that fragment but i keep failing to do that.
This is my main activity
public class MainActivity extends AppCompatActivity {
public int QuestionNum =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivityFragment MainFrag = new MainActivityFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.content, MainFrag).commit();
}
public void Answer1(View view){
QuestionNum++;
Stage StageFrag = new Stage();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content,StageFrag).commit();
}
and this is my fragment
public class Stage extends Fragment {
public Stage() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stage, container, false);
MainActivity Main = new MainActivity();
String QuestionInd[] = getResources().getStringArray(R.array.Qind);
Integer AnswerAnimal[]={R.drawable.anjing,R.drawable.kucing....};
int QNum = Main.QuestionNum;
TextView Question = (TextView) view.findViewById(R.id.Questions);
Question.setText(QuestionInd[Main.QuestionNum]);
ImageButton Ans1 = (ImageButton) view.findViewById(R.id.Choice1);
ImageButton Ans2 = (ImageButton) view.findViewById(R.id.Choice2);
ImageButton Ans3 = (ImageButton) view.findViewById(R.id.Choice3);
ImageButton Ans4 = (ImageButton) view.findViewById(R.id.Choice4);
switch(QNum) {
case 0:
Ans1.setBackgroundResource(AnswerAnimal[0]);
Ans2.setBackgroundResource(AnswerAnimal[1]);
Ans3.setBackgroundResource(AnswerAnimal[2]);
Ans4.setBackgroundResource(AnswerAnimal[3]);
break;
case 1:
Ans1.setBackgroundResource(AnswerAnimal[8]);
Ans2.setBackgroundResource(AnswerAnimal[9]);
Ans3.setBackgroundResource(AnswerAnimal[5]);
Ans4.setBackgroundResource(AnswerAnimal[4]);
break;
}
return view;
}
}
i didnt get error in my logcat. I also try using add but the background didn't change only the fragments keep stacking. Using the attach and retach didnt work too.
Please help me and explain my mistake. i really want to learn about this. Thank you.

First of all, never do this:
MainActivity Main = new MainActivity();
explained here.
Second: Even if you considered an Android Activity as just a normal Java Class, then new MainActivity() means you are creating new instance of that class, so the instance variables will be what or how you defined them i.e public int QuestionNum =0 will remain the same.
Hence the switch statement never comes to case: 1.
What you can do is just call some method like changeImageButtons() on the StageFrag Object you have in the Activity.

Related

Changing TextView Attributes from button onClick not working

So I have a xml fragment called fragment_home. Which has 2 buttons and a textview inside cardview. One of the button (tries to) change the value in the textview. On both the buttons I have an onClick. The tools:context for the fragment is set to .MainActivity. I also have a extend Fragment class which is associated with the xml fragment.
Whenever I try to call anything to change the TextView attributes such as setText,setTextSize I get an exception: java.lang.IllegalStateException: Could not execute method for android:onClick
If I do not have setText, setTextSize, the onClick works.
MainActivity:
public class MainActivity extends AppCompatActivity {
private int textViewData;
private TextView inputDataTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputDataTextView= (TextView)findViewById(R.id.focus_counter);
}
//onClick For One of the buttons
public void increaseNumber(View view) {
textViewData++;
// Crashes When I have This. Doesn't crash when I comment this.
inputDataTextView.setTextSize(60);
// Crashes When I have this. Doesn't crash when I comment this.
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
I feel like It's something to do with my fragment and activity. But I just do not know what the problem is. As soon as I call anything related to the textview in the onClick the app crashes. And the textview in the xml is set to 0 initially and when I increase the number, it increases, so thats working.
Thanks for the help!!
HomeFragment:
public class HomeFragment extends Fragment {
private int textViewData;
private static final String TAG = "MyActivity";
private TextView inputDataTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
inputDataTextView = view.findViewById(R.id.focus_counter);
return view;
}
public void increaseNumber(View view) {
textViewData++;
//inputDataTextView.setText("t");
inputDataTextView.setText(String.valueOf(inputViewData));
//Toast.makeText(getContext(), "Focus Vale = " + inputViewData, Toast.LENGTH_SHORT).show();
}
}
Your inputDataTextView is null because its in fragment but your instantiating it from MainActivity, which is wrong. Move both the onClick methods and view to the fragment java code.
Edit copy theses codes from MainActivity to HomeFragment before onCreateView:
private int textViewData;
private TextView inputDataTextView;
Then these inside onCreateView before the return statement:
inputDataTextView=
(TextView)findViewById(R.id.focus_counter);
Then these method inside your fragment:
public void increaseNumber(View view) {
textViewData++;
inputDataTextView.setTextSize(60);
inputDataTextView.setText(String.valueOf(textViewData);
Toast.makeText(this, "TextView Value = " + textViewData, Toast.LENGTH_SHORT).show();
}
It should work now

how to share content in fragmentPageAdapter

please am sorry to ask this simple question, but have been battling with this problem for the past one week. I will appreciate if anyone can solve this problem for me by coding inside the onclick of the button listener which when clicked it share the content in the fragment or the adapter that extends fragmentStatePageAdapter.
My Activity
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Adapter devicePageAdaptor = new Adapter(getSupportFragmentManager(), getApplicationContext());
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(devicePageAdaptor);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
The Fragment
public class fragment extends Fragment {
public static final String ProverbKey = "proverbKey" ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_device, container, false);
Bundle bundle = getArguments();
if (bundle != null) {
String proverb = bundle.getString(ProverbKey);
setValues(view,proverb);
}
return view;
}
private void setValues(View view, String proverb) {
TextView textView = (TextView) view.findViewById(R.id.textView_proverb);
textView.setText(proverb);
}
}
The Adapter that extends fragmentStateAdapter
public class Adapter extends FragmentStatePagerAdapter {
String[] proverb;
public Adapter(android.support.v4.app.FragmentManager fm,Context context) {
super(fm);
Resources resources = context.getResources();
proverb = resources.getStringArray(R.array.proverb);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString(fragment.ProverbKey, proverb[position]);
fragment deviceFragment = new fragment();
deviceFragment.setArguments(bundle);
return deviceFragment;
}
#Override
public int getCount() {
return proverb.length;
}
}
And my String Array in each fragment which is named proverb
<string-array name="proverb">
<item>A young idler, an old beggar.</item>
<item>Action speaks louder than words.</item>
<item>A hungry man is an angry man.</item>
<item>A living dog is better than a dead lion.</item>
<item>A hedge between keeps friendship green.</item>
<item>A heavy purse gives to a light heart.</item>
<item>A handful of patience is worth more than a bushel of brains</item>
<item>A guilty conscience needs no accuser.</item>
<item>A growing youth has a wolf in his belly.</item>
<item>A good name is better than a good face.</item>
<item>A good beginning makes a good end.</item>
<item>A drop of ink may make a million think.</item>
<item>A dry March, a wet April and a cool May may fill barn and cellar and bring much hay.</item>
</string-array>
//Global Variable
String[] proverb;
//Init on onCreate()
proverb = resources.getStringArray(R.array.proverb);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = viewPager.getCurrentItem();
String itemToShare = proverb[pos];
share(itemToShare);
}
});
private void share(String item) {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_SUBJECT, "Title Of The Post");
share.putExtra(Intent.EXTRA_TEXT, item);
startActivity(Intent.createChooser(share, "Sharing Item!"));
}
Try this and update me if works

How to get values of edittext which is in fragment on button click which is in activity?

signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}

Activity to SherlockFragment

I want to change my app ( extends Activity ) to Fragment ( extends SherlockFragment )
If I change it I have much errors;
public class AlarmClock extends SherlockFragment implements OnClickListener {
This is my onCreateView:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// sanity check -- no database, no clock
if (getContentResolver() == null) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.error))
.setMessage(getString(R.string.dberror))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.create().show();
return;
}
View view = inflater.inflate(R.layout.alarm_clock, container, false);
// menu buttons
add = (ImageButton) findViewById(R.id.ibAdd);
snooze = (ImageButton) findViewById(R.id.ibSnooze);
add.setOnClickListener(this);
snooze.setOnClickListener(this);
mFactory = LayoutInflater.from(this);
mPrefs = getSharedPreferences(PREFERENCES, 0);
mCursor = Alarms.getAlarmsCursor(getContentResolver());
mAlarmsList = (ListView) findViewById(R.id.alarms_list);
mAlarmsList.setAdapter(new AlarmTimeAdapter(this, mCursor));
mAlarmsList.setVerticalScrollBarEnabled(true);
mAlarmsList.setItemsCanFocus(true);
mClockLayout = (ViewGroup) findViewById(R.id.clock);
mQuickAlarm = findViewById(R.id.ibSnooze);
mQuickAlarm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showQuickAlarmDialog();
}
});
setVolumeControlStream(android.media.AudioManager.STREAM_ALARM);
setQuickAlarmVisibility(mPrefs.getBoolean(PREF_SHOW_QUICK_ALARM, true));
return view;
}
There are a lot of errors because there is no Activity.
If is Activity it works.
I use "extends SherlockFragment" because I want to add it to the table.
How fix this problem ? Please help me.
If am right, Fragments must definitely be used in an Activity.
So instead of using this use getActivity(); to get the Activity(which uses this fragment) Context.
something like:
getActivity.finish();
and in case of findViewById(//some Id);
use it like this:
inflatedView.findViewById(//Id);
A Fragment is not a Context (unlike Activity or Application). So quite a few methods are not available to it.
It however has access to the context it is attached to. Usually, you can call getActivity() within the fragment to get it. You should check if the Fragment is part of the activity by using the isAdded() method.
You should do some reading about Fragments, porting existing activities to use Fragments, ... tutorials are available using Google.

Communication between TabActivity and the embedded activity

I am trying to figure out the best practice of communication between a TabActivity and the child activity embedded in this TabActivity.
In my TabActivity, there is a button. When the button is clicked, I want the child activity embedded in this TabActivity to be updated. I wrote the code like below, and just wonder whether it is a good practice. Thanks.
MyTabActivity.java
public class MyTabActivity extends TabActivity implements OnClickListener {
private TabHost m_tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ff_tab_activity);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
m_tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, ChildActivity.class);
spec = m_tabHost.newTabSpec("Tab 1");
spec.setContent(intent);
tabView = (TextView) inflater.inflate(R.layout.tab_indicator, null);
spec.setIndicator(tabView);
m_tabHost.addTab(spec);
m_tabHost.setCurrentTab(0);
ImageView nextButtonIv = (ImageView) findViewById(R.id.next_button);
nextButtonIv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next_button:
synchronized (ChildActivity.class) {
if (null != ChildActivity.s_childActivity) {
ChildActivity.s_childActivity.changeUI();
}
}
break;
}
}
ChildActivity.java
public class ChildActivity extends Activity {
public static ChildActivity s_childActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
synchronized (MatchupsActivity.class) {
s_childActivity = this;
}
setContentView(R.layout.child_activity);
}
public void changeUi() {
code that changes UI
}
protected void onDestroy() {
super.onDestroy();
synchronized (MatchupsActivity.class) {
s_childActivity = null;
}
}
Since TabActivity is an ActivityGroup, I would use one of the following:
getCurrentActivity()
Returns the child tab activity being displayed. In your case, this method will return the instance of ChildActivity being used.
ChildActivity childActivity = (ChildActivity) getCurrentActivity();
getLocalActivityManager().getActivity(String)
Returns the child tab activity given its ID/tab spec name, whatever activity being displayed.
ChildActivity childActivity = (ChildActivity) getLocalActivityManager().getActivity("Tab 1");
I suggest overriding onNewIntent(Intent) in your ChildActivity:
Intent intent = new Intent();
intent.putExtra("xyz", "whatever"); // or a serializable
ChildActivity childActivity = (ChildActivity) getLocalActivityManager().getActivity("Tab 1");
childActivity.onNewIntent(intent);
Let me know if it works!
Seems fine. A couple of notes:
- I see no reason for synchronization.
- I'd replace
ChildActivity.s_childActivity.changeUI();
with
if(ChildActivity.s_childActivity != null){
ChildActivity.s_childActivity.changeUI();
}
or even
try{
ChildActivity.s_childActivity.changeUI();
} catch(Exception e){
//log
}
for added paranoid safety. :)
The way above with
ChildActivity childActivity = (ChildActivity) getLocalActivityManager().getActivity("Tab 1");
childActivity.onNewIntent(intent);
is not very nice. Instead of invoking your activity method directly (it can be null!!!) better do it this way:
Intent intent = new Intent(this, ChildActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(AlbumBrowser.INTENT_EXTRA_FILTER, mediaTitle);
getLocalActivityManager().startActivity("activityIdHere", intent);
Couple of design issues with this, but overall it seems reasonable.
I would forgo the static instance in the ChildActivity class. Why? Well, think about the relationship you're modeling. A TabActivity has a ChildActivity. This is textbook composition, and would be accomplished by adding a ChildActivity field to the TabActivity class, like so:
public class TabActivity {
private ChildActivity child;
//remember to initialize child in onCreate
//then, call methods using child.changeUI();, for example
}
This is better, because A) now I can have multiple instances of TabActivity and ChildActivity that won't interfere with each other (before, it was just a static variable, so only one ChildActivity could be used), and B) the ChildActivity is encapsulated inside the TabActivity class... before, it was a public field, meaning anything can use and modify it (might not be desirable; can often lead to some strange runtime bugs as well as messy, tied-together code) - we changed it to a private field, because we don't really want other classes accessing it in unexpected ways.
The only thing you may need access to from the ChildActivity is the parent (TabActivity). To do this, add the following methods and field to the ChildActivity class, and call the registerParent() method after constructing the ChildActivity:
public class ChildActivity ...{
private TabActivity parent;
public void registerParent(TabActivity newParent){
if (newParent != null){
parent = newParent;
}
}
}
So, if you need access to the parent TabActivity from the child, just call parent.someMethod();
It would also be wise to access fields like parent and child through getters and setters; it might save you some time in the long run.
You can use getParent() to obviate the need to do any of this.
Here's my launcher child class with buttons that switch between activities handled by the tabHost:
public class LaunchPadActivity extends Activity implements OnClickListener {
private static final int ICON_PROFILE = 0;
private static final int ICON_SEARCH = 1;
private static final int ICON_MAP = 2;
private static final int FAVOURITES = 3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launchpad);
GridView launchPad = (GridView) findViewById(R.id.launchpad);
launchPad.setAdapter(new LaunchIconAdapter(this));
}
public class LaunchIconAdapter extends BaseAdapter {
private Context mContext;
// references to our images
private Integer[] mThumbIds = { R.drawable.user, R.drawable.find,
R.drawable.map, R.drawable.favourites, R.drawable.reviews,
R.drawable.news, R.drawable.tutorial, R.drawable.info,
R.drawable.options, };
public String[] texts = { "Profile", "Search", "Map", "Favourites",
"Reviews", "News", "Tutorial", "Info", "Options" };
public LaunchIconAdapter(Context c) {
mContext = c;
}
// Number of thumbs determines number of GridView items
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
// Icon elements
LinearLayout launchIcon;
ImageView launchImage;
TextView launchText;
if (convertView == null) {
launchIcon = (LinearLayout) ((LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.launchicon, null);
} else {
launchIcon = (LinearLayout) convertView;
}
// Add ClickListener with metadata
launchIcon.setTag(new Integer(position));
launchIcon.setOnClickListener(LaunchPadActivity.this);
// Get subviews
launchImage = (ImageView) launchIcon
.findViewById(R.id.launch_image);
launchText = (TextView) launchIcon.findViewById(R.id.launch_text);
// Configure subviews
launchImage.setImageResource(mThumbIds[position]);
launchText.setText(texts[position]);
return launchIcon;
}
}
#Override
public void onClick(View v) {
int position = ((Integer) v.getTag()).intValue();
switch (position) {
case ICON_PROFILE:
Toast.makeText(this, "Profile", Toast.LENGTH_LONG).show();
break;
case ICON_SEARCH:
Toast.makeText(this, "Search", Toast.LENGTH_LONG).show();
((TabActivity) getParent()).getTabHost().setCurrentTab(1);
break;
case ICON_MAP:
Toast.makeText(this, "Map", Toast.LENGTH_LONG).show();
((TabActivity) getParent()).getTabHost().setCurrentTab(2);
break;
case FAVOURITES:
Toast.makeText(this, "Map", Toast.LENGTH_LONG).show();
((TabActivity) getParent()).getTabHost().setCurrentTab(3);
break;
}
}
}
Works like a charm.

Categories

Resources