Sending bundle from same activity to it's fragment - android

I'm trying to code my first big project in Android and it's also first time I'm actually writing here. I've been trying to make this issue work for the whole day in vain, and will really appreciate if someone could show me where I'm wrong. I understand that achieving Fragment fields from the activity is bad practice, but it's the only way I don't receive null in my Fragment TextViews. Otherwise the TextViews are null. I've tried to deal with the bundle in different fragment lifecycle events (onAttach and onCreate), but nothing helped, they still don't see the values from the bundle. Thanks a lot in advance!
And one more question, do I understand right that if I want to send a bundle from one activity to other's activity fragment, the only way is to send it to the other activity and then resend to the fragment or make an interface? Maybe there is some straight way I'm not aware about? Thanks a lot in advance!
Here is my FRAGMENT:
public class MatchFragment extends Fragment {
User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root;
root=inflater.inflate(R.layout.fragment_match,container,false);
Intent intent = getActivity().getIntent();
Bundle bundle = this.getArguments();
if(bundle!=null)
clickedUser = bundle.getParcelable("clickedUser");
else
Toast.makeText(getActivity(),getString(R.string.noMatches),Toast.LENGTH_SHORT).show();
TextView nickNameTv=(TextView)root.findViewById(R.id.matchName);
TextView firstLastNameTv=(TextView)root.findViewById(R.id.firstLastName);
TextView paymentRequiredTv=(TextView)root.findViewById(R.id.paymentRequired);//if payment required - red "payment required", else green "can help for free"
Button mail=(Button)root.findViewById(R.id.mailBtn);
Button call=(Button)root.findViewById(R.id.callBtn);
Button sms=(Button)root.findViewById(R.id.smsBtn);
nickNameTv.setText(clickedUser.nickname);
firstLastNameTv.setText(clickedUser.firstName+" "+clickedUser.lastName);
boolean payment=clickedUser.paymentRequired;
if(payment==true)
{
paymentRequiredTv.setText(getText(R.string.payable));
paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
else
{
paymentRequiredTv.setText(getText(R.string.free));
paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
}
mail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mailIntent = new Intent(Intent.ACTION_SEND);
mailIntent.setType("message/rfc822");
mailIntent.putExtra(Intent.EXTRA_EMAIL, clickedUser.usermail);
mailIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.mailMessage));
// Intent mailer = Intent.createChooser(mailIntent, null);
startActivity(mailIntent);
}
});
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri number = Uri.parse("tel:"+clickedUser.phonenumber);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
});
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.setData(Uri.parse("sms:"+ clickedUser.phonenumber));
startActivity(smsIntent);
}
});
return root;
}
}
and the XML of it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="#android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="LargeText"
android:textColor="#color/colorPrimaryDark"
android:id="#+id/matchName"
android:layout_marginTop="44dp"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/paymentRequired" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/colorPrimaryDark"
android:text="Large Text"
android:id="#+id/firstLastName"
android:layout_below="#+id/profilePicture"
android:layout_alignEnd="#+id/paymentRequired" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:text="#string/call"
android:id="#+id/callBtn"
android:textColor="#android:color/white"
android:layout_alignTop="#+id/smsBtn"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:text="#string/mail"
android:layout_marginStart="36dp"
android:textColor="#android:color/white"
android:id="#+id/mailBtn"
android:layout_alignTop="#+id/callBtn"
android:layout_toEndOf="#+id/callBtn" />
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/orange_blue_ripple_template"
android:textColor="#android:color/white"
android:text="#string/sms"
android:id="#+id/smsBtn"
android:layout_below="#+id/paymentRequired"
android:layout_alignStart="#+id/paymentRequired"
android:layout_marginTop="24dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/profilePicture"
android:layout_below="#+id/matchName"
android:layout_toStartOf="#+id/button2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/paymentRequired"
android:layout_below="#+id/firstLastName"
android:layout_toStartOf="#+id/callBtn" />
</RelativeLayout>
Here is the ACTIVITY:
public class OneMatchActivity extends ToolbarActivity {
User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_match);
Bundle bundle=getIntent().getExtras();
clickedUser=bundle.getParcelable("clickedUser");
MatchFragment matchFragment = new MatchFragment();// or maybe ?? (MatchFragment)(getSupportFragmentManager().findFragmentById(R.id.fragment));
Bundle bundleToFr = new Bundle();
bundleToFr.putParcelable("clickedUser", clickedUser);
matchFragment.setArguments(bundle);
and the XML of the ACTIVITY:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/colorPrimary"
tools:context="hyperactive.co.il.helppool.OneMatchActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="hyperactive.co.il.helppool.MatchFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:background="#drawable/helpinghands"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingTop="50dp"
android:paddingBottom="50dp"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>

//Activity:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.replace(R.id.container, MyFragment.newInstance(arg1, arg2), "tag");
trans.addToBackStack(null).commit();
//Fragment:
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(String arg1, String arg2)
{
MyFragment frag = new MyFragment();
Bundle args = new Bundle();
args.putString("ARG1", arg1);
args.putString("ARG2", arg2);
frag.setArguments(args);
return frag;
}
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
Bundle args = getArguments();
if(args!=null)
{
String arg1 = args.getString("ARG1");
String arg2 = args.getString("ARG2");
}
}
//Xml
//You can use .add instead .replace method. And in the xml layout you need //to change:
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="hyperactive.co.il.helppool.MatchFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true" /> ,
//to this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"/>

MyFragment myF = MyFragment.getInstance(arg1,arg2);
fragmentManager.add(myF);
public class MatchFragment extends Fragment{
public static MatchFragment getInstance(String a, String b){
MyFragment myF = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("a", a);
bundle.putString("b", b);
myF.setArguments(bundle);
return myF
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
if (b != null) {
b.getString("a");
b.getString("b");
}
}
}

Instead of passing the parameters in the form of Bundle from Activity to its Fragment, pass the parameters to the the Fragment via a static factory method that instantiates your fragment
MyFragment myF = My fragment.newInstance(arg1,arg2);
fragmentManager.replace(myF);
...

Related

Passing value of textview from one activity to another by pressing a button [duplicate]

This question already has answers here:
How to pass a value from one Activity to another in Android?
(7 answers)
Closed 7 years ago.
This is my 1st time working in AndroidStudio. What I want to do is I want to pass the value generated in the txresult(activity_main.xml), the one generated after it scans. I want to pass that value after I push Yes, to my SecondActivity.java, and to be able to display the value.
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="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
public static final int REQUEST_CODE = 0;
private TextView txResult;
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button2).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView)findViewById(R.id.txResult);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("textViewText", textView.getText().toString());
startActivity(intent);
}
});
}}
SecondActivity.java
package br.exemplozxingintegration;
import android.app.Activity; import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle extras = getIntent().getExtras();
if (extras != null) {
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(extras.getString("textViewText"));
}
}}
Activity_second.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.53" /> </LinearLayout>
Using Intent.putExtra() you can do what you want to do.
Intent intent = new Intent( this, MyActivity.class );
intent.putExtra( "paramName", textview.getText().toString() );
startActivity( intent );
You can get the values by using
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String myParam=extras.getString("paramName");
}
You would use this part on the second activity, specifically the onCreate methode.
Try this:
Intent i=new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("result",txResult.getText());
startActivity(i);
and in your SecondActivity:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String strResult=extras.getString("result");
}
strResult gives your string passed from your previous Activity
FirstActivity.java
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.text_view);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("textViewText", textView.getText().toString());
startActivity(intent);
}
});
}}
first_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view"
android:text="123"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Text to Second Activity"/>
</LinearLayout>
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Bundle extras = getIntent().getExtras();
if (extras != null) {
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(extras.getString("textViewText"));
}
}}
SecondActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Why is my TextView not centerInParent in my ViewPager fragment?

My TextView has layout_centerInParent="true" and looks good in the layout preview in Android Studio, but when I compile and run the "Let's Get Started" text ends up near the bottom as shown below. Why is this happening?
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/intro_background"
android:background="#color/primary">
<TextView
android:id="#+id/tv_welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxWidth="240sp"
android:gravity="center"
android:textSize="45sp"
android:textStyle="bold"
android:textColor="#color/white"
android:text="Let\'s Get Started!"
/>
<Button
android:id="#+id/btn_add_course"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_not_now"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp"
android:background="#drawable/btn_primary_with_white"
android:paddingBottom="10dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="10dp"
android:text="Add My First Course"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:id="#+id/tv_not_now"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:maxWidth="280sp"
android:layout_gravity="center_horizontal"
android:gravity="left"
android:textStyle="italic"
android:textSize="16sp"
android:textColor="#color/white"
android:text="#string/intro_not_now"
/>
</RelativeLayout>
Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="#drawable/nav_header1" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="3dp"
android:layout_marginTop="-25dp"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
Activity:
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new Adapter_Intro(getSupportFragmentManager()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
}
Fragment:
public class IntroFragment extends Fragment {
private static final String BACKGROUND_COLOR = "backgroundColor";
private static final String PAGE = "page";
private int mBackgroundColor, mPage;
public static IntroFragment newInstance(int backgroundColor, int page) {
IntroFragment frag = new IntroFragment();
Bundle b = new Bundle();
b.putInt(BACKGROUND_COLOR, backgroundColor);
b.putInt(PAGE, page);
frag.setArguments(b);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!getArguments().containsKey(BACKGROUND_COLOR))
throw new RuntimeException("Fragment must contain a \"" + BACKGROUND_COLOR + "\" argument!");
mBackgroundColor = getArguments().getInt(BACKGROUND_COLOR);
if (!getArguments().containsKey(PAGE))
throw new RuntimeException("Fragment must contain a \"" + PAGE + "\" argument!");
mPage = getArguments().getInt(PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Select a layout based on the current page
int layoutResId;
switch (mPage) {
case 0:
layoutResId = R.layout.fragment_intro_welcome;
break;
default:
layoutResId = R.layout.fragment_intro_start;
}
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(layoutResId, container, false);
// Set the current page index as the View's tag (useful in the PageTransformer)
view.setTag(mPage);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Set the background color of the root view to the color specified in newInstance()
View background = view.findViewById(R.id.intro_background);
background.setBackgroundColor(mBackgroundColor);
}
}
It seems that Android Studio is not accurate while rendering your layout.
I "measured" your screenshot using Gimp - as you can see, TextView is positioned exactly to the center of it parent, between top picture and bottom:
Your TextView is well centered inside the fragment, but not inside the activity.
Because in your activity, there is the ImageView that takes some height in the top.

Android - Call Method With A Button From XML

I've got an app based on Sliding Tabs layout. I want to call the addMedicine method in the PageFragment class from an XML layout with a Button. The issue is that i cannot assign the method to the Button onClick event.
Here's the PageFragment class:
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
// TEMP VARIABLES //
ListView ItemsLst;
String[] Items = {"Medicine 1", "Medicine 2", "Medicine 3"};
TextView output;
EditText nameFld;
EditText formatFld;
EditText amountFld;
EditText exp_dateFld;
EditText timeFld;
DBManager dbAdapt = new DBManager(getActivity());
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
switch(mPage)
{
case 1:
view = inflater.inflate(R.layout.layout_sqltest, container, false);
nameFld = (EditText) view.findViewById(R.id.nameFld);
formatFld = (EditText) view.findViewById(R.id.formatFld);
amountFld = (EditText) view.findViewById(R.id.amountFld);
exp_dateFld = (EditText) view.findViewById(R.id.exp_dateFld);
timeFld = (EditText) view.findViewById(R.id.timeFld);
return view;
case 2:
view = inflater.inflate(R.layout.layout_settings, container, false);
return view;
case 3:
view = inflater.inflate(R.layout.layout_info, container, false);
return view;
}
return view;
}
public void addMedicine() // The method i want to call
{
String name = nameFld.getText().toString();
String format = formatFld.getText().toString();
int amount = Integer.parseInt(amountFld.getText().toString());
String exp_date = exp_dateFld.getText().toString();
String time = timeFld.getText().toString();
long id = dbAdapt.addMedicine(name, format, amount, exp_date, time);
}
}
And here is the layout_sqltest XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/nameFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Format"
android:id="#+id/formatLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/formatFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Amount"
android:id="#+id/amountLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/amountFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Expiration Date"
android:id="#+id/exp_dateLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/exp_dateFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Time"
android:id="#+id/timeLbl"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/timeFld"
android:layout_gravity="center_horizontal"
android:inputType="text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Medicine"
android:id="#+id/addMedicineBtn"
android:layout_gravity="center_horizontal" />
</LinearLayout>
The addMedicineBtn is the button i want to call the method with.
Someone can help me? I really need that!
Thank you in advance!
EDIT: I tried giving to addMedicine method the View param, but it still doesn't appear in the available methods for the addMedicineBtn in the onClick properties (I'm using Android Studio).
Try to use onClickListener
view.findViewById(R.id.addMedicineBtn).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addMedicine();
}
});
You must add tools:context="PageFragment" line to the container (LinearLayout) of PagerFragment's layout file (layout_sqltest). Then onClick() method will find methods in PagerFragment class.

ImageButton onClick not called in RelativeLayout in a Fragment using a transparent ActionBar

any ideas why my ImageButton isn't working in my Fragment?
The ImageButton contains a Drawable and is transparent.
When I place it in my RelativeLayout below, its working...
<RelativeLayout
android:id="#+id/rl_newsdet_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/bg"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_newsdet_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:layout_marginTop="7dp"
android:textSize="20sp"
android:layout_centerHorizontal="true"
/>
<ImageButton
android:id="#+id/btn_newsdet_back"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/bt_back"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize"
android:background="#color/white"
android:gravity="left"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_newsdet_name"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:textStyle="bold"
android:textColor="#color/cyan"
android:background="#color/grey"
android:paddingLeft="1dp"
android:paddingRight="1dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_newsdet_time"
android:textColor="#color/white"
android:textSize="18sp"
android:layout_toRightOf="#+id/tv_newsdet_name"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:background="#color/grey"
android:layout_marginTop="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/tv_newsdet_text"
android:layout_marginLeft="10dp"
android:layout_marginTop="1dp"
android:layout_below="#+id/tv_newsdet_name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
My onClickListener with AndroidAnnotations
#ViewById
ImageButton btn_newsdet_back;
#Click(R.id.btn_newsdet_back)
void back() {
Log.i(TAG,"back");
mActivity.popFragments();
}
EDIT
onClick is working (called), when its below the TextView. Can anybody explain why?
If, as you said, everything works when you put the button inside the RelativeLayout below the reason should be that the second RelativeLayout has its parameters declared as:
android:layout_width="match_parent"
android:layout_height="match_parent"
Which means it is "filling" its parent, that is the original RelativeLayout containing the button. It's like you're creating a layer that covers the button and keeps any interaction with it from working. When you click on the button, you're actually clicking on the second RelativeLayout.
I didn't actually tried this, but you should consider setting:
android:layout_below="#id/btn_newsdet_back"
On the RelativeLayout below the button.
You can try this code:
This is code of Fragment: TestFragment.java
public class TestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_one, container, false);
ImageButton button = (ImageButton) view.findViewById(R.id.img2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Click on fragment ",
Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is layout of 'TestFragment`
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:id="#+id/img2"
android:layout_width="100dp"
android:layout_height="80dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
This is code of MainActivity.java
public class MainActivity extends FragmentActivity {
ImageButton imgButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
FragmentManager fragmentManager = getSupportFragmentManager();
TestFragment fragment = (TestFragment) fragmentManager
.findFragmentById(R.id.fragment);
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// fragmentTransaction.add(fragment, "");
fragmentTransaction.commit();
}
}
This is layout of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/fragment"
android:name="com.alarmdemo.TestFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Here ImageButton is placed in a Fragment and it is working fine.
No need to add clickable in image button .Try following:
<ImageButton
android:id="#+id/btn_newsdet_back"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="mymethod"
android:src="#drawable/bt_back"
/>
add in java
public void mymethod(View v)
{
//your method
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sample,
container, false);
addListenerOnButton();
}
private void addListenerOnButton() {
imageButton = (ImageButton) rootview.findViewById(R.id.imageButton1);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(MainActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
});
}
I solved it.
The problem was I was using a transparent Actionbar which was the overlay I was looking for.
The following line in my onCreate() solved this:
getActivity().getActionBar().hide();

Access fragment controls from FragmentActivity

I have a FragmentActivity that should hold 2 Fragments. Each fragment has it's own layout with a table in it. I need to access the tables from the fragments' layouts from within the FragmentActivity to put some data that I read from an XML file. My problem is that when I use
tableOrders = (TableLayout)findViewById(R.id.tabel1);
it returns null. Now, I know that items from layouts can only be accessed before they have been inflated, and I've done that in the FragmentActivity before trying to call findViewById(). Here is the code for what I've tried:
The onCreate of the FragmentHolder.java that is derived from FragmentActivity:
private TableLayout tableOrders = null;
private TableLayout tableExecutions = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_holder);
initialisePaging();
//View orderFragment = (View)findViewById(R.layout.fragment_orders);
tableOrders = (TableLayout)/*orderFragment.*/findViewById(R.id.tabel1);
//View execFragment = (View)findViewById(R.layout.executions_fragment);
tableExecutions = (TableLayout)/*execFragment.*/findViewById(R.id.tabel2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
logedUser = (User) bundle.getSerializable("user");
AssetManager am = getApplicationContext().getAssets();
String xmlContentOrders = XMLfunctions.getXml(am, "ordersData.xml");
populateOrdersTable(xmlContentOrders);
String xmlContentExecutions = XMLfunctions.getXml(am, "executionsData.xml");
populateExecutionsTable(xmlContentExecutions);
}
The fragment class (don't know if it helps):
public class OrdersFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
return view;
}
}
The fragment class (don't know if it helps):
public class OrdersFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
return view;
}
}
And the .xml file for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tabel1header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/tablebgcolor" >
<TableRow >
<TextView
android:id="#+id/ordersHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:text="#string/orders"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/ordersTable"
style="#style/HeaderRow" >
<TextView
android:id="#+id/textSymbol"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/symbol"
style="#style/HeaderText" />
<TextView
android:id="#+id/textSide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/side"
style="#style/HeaderText" />
<TextView
android:id="#+id/textPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/price"
style="#style/HeaderText" />
<TextView
android:id="#+id/textQuantity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/quantity"
style="#style/HeaderText"/>
<TextView
android:id="#+id/textRemaining"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/remanent"
style="#style/HeaderText" />
</TableRow>
</TableLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TableLayout
android:id="#+id/tabel1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/tablebgcolor">
</TableLayout>
</ScrollView>
</LinearLayout>
With that said hope someone has a solution for this (probably it's something easy that I missed).
Edit: The code I use to put the Fragments on the FragmentActivity:
private void initialisePaging() {
OrdersFragment fragmentOne = new OrdersFragment();
ExecutionsFragment fragmentTwo= new ExecutionsFragment();
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(fragmentOne);
pagerAdapter.addFragment(fragmentTwo);
ViewPager viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
}

Categories

Resources