How to get instance of view's parent fragment: - java

I have a fragment with an XML layout file. in it I have an 2 clickable ImageViews.
for each ImageView I set an onClick method for example: android:onClick="commentFragmentRemoveOnClick".
In the FragmentActivity (The Activity no the Fragment) I defined it this way:
public void commentFragmentRemoveOnClick(View v)
{
}
No this Fragment is of type CommentFragment and it has a public void getFragmentTag()method
to get it's tag that I save in earlier time. I need to get an instance of the fragment in which the image was clicked to get it's tag.
I tried:
((CommentFragment)v).getParentFragment().getFragmentTag();
and:
((CommentFragment)v).getParent().getFragmentTag();
but eclipse gives me error on both of them, how is this done properly?
To make it more clear this is my CommentFragment:
public class CommentFragment extends Fragment {
private final static String TAG = CommentFragment.class.getSimpleName();
private String fragmentTag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.comment_fragment_layout,
container, false);
Bundle bundle = getArguments();
String text = bundle.getString("comment");
String fullUser = bundle.getString("user");
String user = fullUser.substring(0, fullUser.indexOf("#"));
String at = bundle.getString("at");
TextView tvCmment = (TextView) rootView.findViewById(R.id.tvComment);
TextView tvUser = (TextView) rootView.findViewById(R.id.tvUser);
TextView tvAt = (TextView) rootView.findViewById(R.id.tvDate);
tvCmment.setText(text);
tvUser.setText(user);
tvAt.setText(at);
return rootView;
}
public void setText(String item)
{
TextView view = (TextView) getView().findViewById(R.id.tvComment);
view.setText(item);
}
public void setFragmentTag(String tag)
{
this.fragmentTag = tag;
}
public String getFragmentTag()
{
return this.fragmentTag;
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llCommentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/try2">
<TextView
android:id="#+id/tvUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvComment"
android:layout_alignParentTop="true"
android:background="#color/my_gray"
android:text="demo"
android:textStyle="bold"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvDate"
android:padding="5dp"
android:text="This task is described in more details if you click on it."
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray"
android:layout_toRightOf="#+id/tvUser"
android:background="#color/my_gray"
android:text="at" />
<TextView
android:id="#+id/tvDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAt"
android:layout_alignBottom="#+id/tvAt"
android:layout_toRightOf="#+id/tvAt"
android:background="#color/my_gray"
android:text="12/02"
android:textColor="#color/my_even_darker_gray" />
<ImageView
android:id="#+id/iEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvComment"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentEditOnClick"
android:src="#drawable/add_comment_button" />
<ImageView
android:id="#+id/iRemove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/iEdit"
android:layout_toRightOf="#+id/iEdit"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentRemoveOnClick"
android:src="#drawable/add_comment_button" />
</RelativeLayout>
I would love for a little assistance.
Thanks.

I have a general advice for you that would solve your problem and help you in the future -
don't use android:onClick in the xml file, use setOnClickListener in the code itself - need to avoid mixing your views with other parts of the app as much as possible.
Try to keep the Fragment independent of its activity.
If the image is part of the fragment, why does the listener is part of the FragmentActivity?
Use setOnClickListener in the fragment itself, and you might be able to use this Framgent in other pats of the app without being depended on the Activity.
It would also solve your problem of identifying the fragment in which the image was clicked.

v is not an instance of Fragment, that's why Eclipse does not like your code. If you want the instance of a fragment you have to use the FragmentManager and one of its findFragmentByXXX methods.

To get the instance of the fragment that the ImageView was clicked in I did the following:
in the Fragment I set two onClickListeners for both of the images like this:
iEdit = (ImageView)rootView.findViewById(R.id.iEdit);
iEdit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed edit button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentEditOnClick(fragmentTag);
}
});
iRemove = (ImageView)rootView.findViewById(R.id.iRemove);
iRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed remove button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentRemoveOnClick(fragmentTag);
}
});
and in the fragment activity I defined those two methods like this:
public void commentFragmentRemoveOnClick (String tag)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentByTag(tag)).commit();
}
for removing the fragment, and Now I'm working on editing the fragment.

Related

Dynamically want to update the text in edit Text from admin end and should reflect updated text in user end

I have created 3 fragments for one of my project ..this is one of them. So basically I want When ever the admin(aAccountFragment) will click on the update quote button the quote should be updated and should be reflected in AccountFragment.xml file in the user end.
For this in the admin(aAccountFragment) side I have provided and edit text where the admin can update the quote every 24hrs.and in the user end(AccountFragment) the user can only see the updated quote when ever the admin will update the quote because at user end textview is provided and in the admin end EditText is provided.
For this I have attached my aAccountFragment.xml, AccountFragment.xml,AccountFragment.java,aAccountFragment.java code.
This is my aAccountFragment.xml code
<?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=".aAccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<EditText
android:layout_width="323dp"
android:layout_height="111dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="21dp"
android:layout_marginBottom="273dp"
android:text="-She decided to start living the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="107dp"
android:layout_marginBottom="177dp"
android:background="#color/LightBlue"
android:text="UPDATE QUOTE"
android:textColor="#color/black"
android:textSize="20sp" />
<Button
android:id="#+id/logout1"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="43dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my aAccountFragment.java code.
public class aAccountFragment extends Fragment {
Button logout1;
public aAccountFragment() {
// 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.afragment_account, container, false);
logout1 = view.findViewById(R.id.logout1);
logout1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), aloginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
this is my AccountFragment.xml code.
<?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=".AccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<TextView
android:layout_width="296dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="49dp"
android:layout_marginBottom="272dp"
android:text="-She decided to start living
the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:id="#+id/logout"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="28dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my AccountFragment.java code.
public class AccountFragment extends Fragment {
Button logout;
public AccountFragment() {
// 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_account, container, false);
logout = view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), loginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
STEP-1: To take quote input from edittext inside AdminFragment.java. I am not posting it's xml file as nothing important there except an EditText. You can put it inside any Activity.
AdminFragment.java
public class AdminFragment extends Fragment {
public static AdminFragment newInstance() {
return new AdminFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
EditText quoteEditText = view.findViewById(R.id.quote_et);
Button quoteBtn = view.findViewById(R.id.quote_btn);
quoteBtn.setOnClickListener(v -> {
String quote = quoteEditText.getText().toString();
if (quote.isEmpty()){
Toast.makeText(getContext(),"Please Enter Quote!",Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
intent.putExtra("quote",quote);
startActivity(intent);
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
STEP-2:
As you would have declared BottomNavigationActivity which would have 3 fragments namely SnapFragment.java , HomeFragment.java and AccountFragment.java. Quote text will be received from AdminFragment.java while click on updateQuote button inside BottomNavigationActivity. Once quote is received inside BottomNavigationActivity, I am opening 3rd Fragment i.e AccountFragment to show quoted text.
BottomNavigationActivity.java
public class BottomNavigationActivity extends AppCompatActivity {
String updatedQuote = "";
BottomNavigationViewModel bottomNavigationViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
bottomNavigationViewModel = new ViewModelProvider(this).get(BottomNavigationViewModel.class);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_snap, R.id.navigation_home, R.id.navigation_account)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
updatedQuote = getIntent().getStringExtra("quote");
Log.d("tisha==>>","Quote = "+updatedQuote);
bottomNavigationViewModel.setQuoteLiveData(updatedQuote);
// Below I am selecting 3rd Fragment to show Quote
navView.setSelectedItemId(R.id.navigation_account);
}
}
activity_bottom_navigation.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am using ViewModel here, because it will be easier to pass quote data from current activity to AccountFragment.java as AccountFragment is not instantiated by it's constructor here. BottomNavigationViewModel is responsible for storing quote and provide wherever it is required.
BottomNavigationViewModel.java
public class BottomNavigationViewModel extends ViewModel {
private final MutableLiveData<String> quoteLiveData;
public String getQuoteLiveData(){
return quoteLiveData.getValue();
}
public void setQuoteLiveData(String quote){
quoteLiveData.setValue(quote);
}
public BottomNavigationViewModel(){
quoteLiveData = new MutableLiveData<>();
}
}
STEP-3:
Now inside AccountFragment, I just get the view model which is created inside BottomNavigationActivity and collecting quote from that and displaying it in TextView.
AccountFragment.java
public class AccountFragment extends Fragment {
private String mQuote;
private BottomNavigationViewModel bottomNavigationViewModel;
public AccountFragment() {
// Required empty public constructor
}
public static AccountFragment newInstance(String quote) {
return new AccountFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bottomNavigationViewModel = new ViewModelProvider(requireActivity()).get(BottomNavigationViewModel.class);
mQuote = bottomNavigationViewModel.getQuoteLiveData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
TextView quoteView = view.findViewById(R.id.quote_tv);
quoteView.setText(mQuote);
}
}

NullPointerException in button onClick in fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have two buttons and an EditText in a fragment. When I click the addMusicButton, I want it to disappear and make newMusic(my EditText) and confirmAddButton appear. If I only change the visibility of the addMusicButton in the onClick method, it works, but if I try to change the visibility of newMusic or confirmAddButton in the onClick method, it gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setVisibility(int)' on a null object reference
and my app crashes. I don't understand why it's saying my button is null because I initialized it right before I changed the visibility in the onClick method(the same thing happens if I try to change the visibility of the EditText). I am able to change the visibility of both my buttons and my EditText in onCreate, just not in onClick. I thought it might be because newMusic and confirmAddButton were in a different linear layout from addMusicButton, so I tried moving them all to one layout and it still gave me the same error.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/addMusicButton"
android:layout_width="match_parent"
android:layout_height="109dp"
android:layout_weight="1"
android:text="#string/add_music" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="109dp"
android:layout_weight="1"
android:orientation="horizontal">
<EditText
android:id="#+id/newMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="330dp"
android:autofillHints=""
android:ems="10"
android:gravity="left|center_vertical"
android:inputType="textAutoComplete" />
<Button
android:id="#+id/confirmAddButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center|center_vertical"
android:text="#string/add" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="585dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/musicLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</LinearLayout>
And my fragment code
public class MusicFragment extends Fragment implements View.OnClickListener {
private MusicViewModel musicViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
musicViewModel = ViewModelProviders.of(this).get(MusicViewModel.class);
View root = inflater.inflate(R.layout.fragment_music, container, false);
Button addMusicButton = root.findViewById(R.id.addMusicButton);
EditText newMusic = root.findViewById(R.id.newMusic);
Button confirmAddButton = root.findViewById(R.id.confirmAddButton);
newMusic.setVisibility(View.GONE);
confirmAddButton.setVisibility(View.GONE);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view) {
Button addMusicButton = view.findViewById(R.id.addMusicButton);
Button confirmAddButton = view.findViewById(R.id.confirmAddButton);
EditText newMusic = view.findViewById(R.id.newMusic);
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}
}
Instead of using separate initialization, you have to use only one initialization which is at onCreateView method only. And declare Button and EditText outside the method.
Try this code:
Button addMusicButton, confirmAddButton ;
EditText newMusic;
In OnCreateView method :
addMusicButton = root.findViewById(R.id.addMusicButton);
newMusic = root.findViewById(R.id.newMusic);
confirmAddButton = root.findViewById(R.id.confirmAddButton);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}
Why your again initialize Button addMusicButton , Button confirmAddButton ,EditText newMusic that is why your getting null pointer exception so please remove onclick initialize Button , EditText
Declare the view(Button, EditText, TextView...) outside onCreateView method if you want to perform some operations. So, try the below code.
public class MusicFragment extends Fragment implements View.OnClickListener {
private MusicViewModel musicViewModel;
private Button addMusicButton, confirmAddButton;
private EditText newMusic;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
musicViewModel = ViewModelProviders.of(this).get(MusicViewModel.class);
View root = inflater.inflate(R.layout.fragment_music, container, false);
addMusicButton = root.findViewById(R.id.addMusicButton);
newMusic = root.findViewById(R.id.newMusic);
confirmAddButton = root.findViewById(R.id.confirmAddButton);
newMusic.setVisibility(View.GONE);
confirmAddButton.setVisibility(View.GONE);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}
}

Android Finding Fragment TextView from Parent Class

I've seen similar questions to mine here, but none of the solutions have helped (I've tried many).
So I have a fragment, which I'm create an instance of both in my main activity and in another activity. The fragment has methods to change various TextViews, and everything works great when I call those methods from my main activity. However, when I try to do the same in my other activity, I keep getting a null pointer exception that the textView isn't found. Here is the relevant code:
activity where it doesn't work:
TextView p1n;
TextView p2n;
TextView p1s;
TextView p2s;
ScoreFragment SF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tic_tac_toe);
SF = new ScoreFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.frag_frame_ttt, SF);
ft.commit();
Intent intent = getIntent();
Log.d(jl, intent.getStringExtra(P1_NAME_KEY));
if (intent != null) {
if (intent.getStringExtra(P1_NAME_KEY) != null && p1n != null) {
SF.setp1name(intent.getStringExtra(P1_NAME_KEY));
}
if (intent.getStringExtra(P2_NAME_KEY) != null && p2n != null) {
SF.setp2name(intent.getStringExtra(P2_NAME_KEY));
}
if (p1s != null) {
SF.setp1score(intent.getIntExtra(P1_SCORE_KEY, 0));
}
if (p2s != null) {
SF.setp2score(intent.getIntExtra(P2_SCORE_KEY, 0));
}
Log.d(jl, Integer.toString(intent.getIntExtra(P2_SCORE_KEY, 0)));
}
Since p1n, p2n, p1s, and p2s are always null, nothing happens.
Here is the frame layout i'm trying to put the fragment in,
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/frag_frame_ttt"
android:paddingBottom="20dp"
/>
and here is my relevant fragment code:
...
TextView p1name;
TextView p2name;
TextView p1score;
TextView p2score;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_score, container, false);
p1name = (TextView) v.findViewById(R.id.p1_name);
p2name = (TextView) v.findViewById(R.id.p2_name);
p1score = (TextView) v.findViewById(R.id.p1_score);
p2score = (TextView) v.findViewById(R.id.p2_score);
Log.d(jl, "onCreateView successful");
return v;
}
public void setp1name(String name) {
p1name.setText(name);
}
public void setp2name(String name) {
p2name.setText(name);
}
public void setp1score(int score) {
p1score.setText(Integer.toString(score));
}
public void setp2score(int score) {
p2score.setText(Integer.toString(score));
}
and the relevant fragment xml:
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Player 1"
android:id="#+id/p1_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" : " />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/p1_score"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Player 2"
android:id="#+id/p2_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" : " />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/p2_score"/>
</LinearLayout>
</LinearLayout>
So after doing some debugging I am quite certain that the issue has to do with the findViewById method in onCreateView() not finding anything, but I've tried moving where I findViewById (such as in each method where the text is being set), but it still hasn't worked.
Any help would be much appreciated.
Got it!
Aside from my stupid bug in my activity where I only set the text if the textview variables (the ones I never set) aren't null...
I had to move all of the code pertaining to my fragment (except for the initialize and the add / commit) from onCreate to onStart. Guess I was trying to preform actions on these textviews before the fragment actually inflated(? sorry I'm new to android, this may be incorrect).

Android: Scrolling from one Fragment to another through a ViewPager

I have implemented a ViewPager which connects multiple Fragments together to give off that 'scrolling view' experience as you might already know. Anyhow I have a button on my first fragment that needs to scroll the user to the second fragment. How do I get this done folks? Here's my code:
ViewPager XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
Fragment 1:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="left"
android:layout_marginLeft="15dp"
android:layout_marginTop="25dp"
android:text="Step 1"
android:textColor="#ffffff"
android:textSize="50dp" />
<Button
android:id="#+id/step1Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="5sp"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="Next Step"
android:textColor="#FFFFFF"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
In order to make this post short, let's say the second fragment has the same XML.
So we have TWO fragments. Here's the fragment java class:
public class RegisterPageOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.registration_page1, container, false);
Button nextStep = (Button) v.findViewById(R.id.step1Btn);
nextStep.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Where I want to call the SECOND FRAG
}
});
return v;
}
public static RegisterPageOne newInstance(String text) {
RegisterPageOne f = new RegisterPageOne();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
help me out please :)
You can use the setCurrentItem(int item,boolean smoothScroll) method of your viewPager object to achieve this. Here is the documentation.
Saw your followup question about how to refer to the ViewPager, from your Fragment. It's pretty convoluted, for a relative newbie like me, but, I think I can get all of it... I'll give you what I did in my code. Set up a listener in the ViewPager:
public class PageViewActivity extends FragmentActivity
implements PageDisplayPortFrag.OnLinkExpectedListener {
...
}
This gets referenced in your Fragment:
private OnLinkExpectedListener mListenerLink;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListenerLink = (OnLinkExpectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLinkExpectedListener");
}
}
#Override
public void onDetach() {
mListenerLink = null;
super.onDetach();
}
// THIS IS THE METHOD CALLED BY THE BUTTON CLICK !!!
public void linkExpected(String ticker) {
if (mListenerLink != null) {
mListenerLink.onLinkActivity(ticker);
}
}
public interface OnLinkExpectedListener {
public void onLinkActivity(String ticker);
}
And, then, a method gets called in the ViewPager:
#Override
public void onLinkActivity(String ticker) {
// receive ticker from port click; user wants to view page in webview, for this security
//Toast.makeText(this, "Ticker item clicked: " + ticker, Toast.LENGTH_SHORT).show();
// NEHARA, YOU MAY OR MAY NOT NEED TO DO STUFF HERE
// THIS IS WHAT I NEEDED TO DO; LEAVING IT FOR THE
// getFragmentTag() EXAMPLE -- WHICH CAME FROM Stack Overflow POSTERS
// get all-important fragment tag
String frag_Tag = getFragmentTag(pager.getId(),1);
// use tag to get the webview fragment
PageXYZWebviewFrag xyzWeb = (PageXYZWebviewFrag)
getSupportFragmentManager().findFragmentByTag(frag_Tag);
// send request to the webview fragment
xyzWeb.loadPageForSelectedSecurity(ticker);
// SET THE DESIRED FRAGMENT, assumes I know the fragment number
// from when I set up the ViewPager
// switch to the webview fragment
pager.setCurrentItem(1);
}
// fragment tag getter -- very important, yet has been elusive
private String getFragmentTag(int viewPagerId, int fragmentPosition) {
return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
}

how to check the checkbox when the layout is clicked?

I have a relative layout. In that relative layout i have a textview at left end and check box at right end. Now
what i want is, when i clicked the entire layout( above relative layout) the check box need to check. any please
help me.
<RelativeLayout
android:id="#+id/layoutavailable"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/layouttaxexempt"
android:layout_marginTop="25dp"
>
<TextView
android:id="#+id/txt_avl"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:hint="IsAlwaysAvailable"
android:textSize="20sp"
android:textColorHint="#color/white"
android:layout_marginTop="5dp"
android:layout_marginLeft="13dp"
/>
<CheckBox
android:id="#+id/c_avl"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"/>
</RelativeLayout>
Code:
public void onClick(View v) {
if (checkbox.isChecked()){
checkbox.setChecked(false);
}
else {
checkbox.setChecked(true);
}
}
Set the listener to the layout
CheckBox cBox = (CheckBox) findViewById(R.id.c_avl);
findViewById(R.id.layoutavailable).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cBox.setChecked(!cBox.isChecked());
}
});
Use CheckedTextView instead of normal TextView.
And make CheckedTextView width and height to match_parent"
Just try this:
public class MainActivity extends Activity {
RelativeLayout layout;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb=(CheckBox)findViewById(R.id.checkBox1);
layout = (RelativeLayout) findViewById(R.id.layoutavailable);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
cb.setChecked(true);
return false;
}
});
}
you can do by following way
yourRelativeLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
youCheckbox.setChecked(!(test.isChecked()));
}
});
First make your Relative Layout clickable by writing the given code in your Relative Layout Tag body, and also assign the id to your layout.:-
android:clickable="true"
android:id="#+id/rl"
Then in your Activity Java file, write the code in your on create instance:-
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
Relative Layout rl = (LinearLayout)findViewById(R.id.rl);
final CheckBox c_avl = (CheckBox)findViewById(R.id.checkBox1);
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
c_avl.setChecked(true);
}
});
}
This will certainly solve your problem, indeed.
You can also achieve this by using the toggle() method of the CheckBox class. Please note that when using the toggle method, there won't be any animation. The way that I fixed that issue was by overriding the toggle method, and defining my own toggle.
private RelativeLayout layoutAvailable = findViewById(R.id.layoutavailable);
private CheckBox cAvl = findViewById(R.id.c_avl);
layoutavailable.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
cAvl.toggle();
}
})
Just pass the state of the parent RelativeLayout to it's child CheckBox
set RelativeLayout clickable, and add an attribute android:duplicateParentState to CheckBox
<RelativeLayout
android:id="#+id/layoutavailable"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/layouttaxexempt"
android:layout_marginTop="25dp"
android:clickable="true"
>
<TextView
android:id="#+id/txt_avl"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:hint="IsAlwaysAvailable"
android:textSize="20sp"
android:textColorHint="#color/white"
android:layout_marginTop="5dp"
android:layout_marginLeft="13dp"
/>
<CheckBox
android:id="#+id/c_avl"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:duplicateParentState='true'
android:layout_marginTop="5dp"/>
</RelativeLayout>

Categories

Resources