getViewByID imagebutton is returning null - android

I have an imageButton on my xml:
<ImageButton
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:id="#+id/star"
android:background="#drawable/star"
android:layout_below="#+id/releaseDate"
android:layout_alignLeft="#+id/releaseDate"
android:layout_alignStart="#+id/releaseDate" />
I want to add the action of the button, but the problem is that the imageButton I created is returning null when fetching the imagebutton on xml with findViewById:
public class DetailActivity extends AppCompatActivity {
ImageButton ib;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailActivityFragment())
.commit();
ib = (ImageButton)findViewById(R.id.star);
if(ib != null) {
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(null, "Image Clicked!");
}
});
}
}
}

Related

Open and close fragment from the same button?

I have the activity that have fragment. Now I have button that open the fragment. I am wondering how I can use the same button for openning and closing fragment?
My code is:
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.frgmCont, frag1);
fTrans.commit();
}
}
XML file of MainActivity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.myapplication5.MainActivity">
<Button
android:id="#+id/reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Registration"
android:background="#drawable/add_btn"
android:layout_margin="10dp"
android:onClick="openFragment"
/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
And here is the fragment:
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, null);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
}
}
change your activity code to this
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
if(flag) {
fTrans.remove(frag1);
} else {
fTrans.add(R.id.frgmCont, frag1);
}
flag = !flag;
fTrans.commit();
}
}

On orientation change button touchlistener not working

I have two layouts table.xml(port) and table.xml(land) which from there names one of the landscape and other for the protrait.
I have included this layout in another layout called fragment_test.xml like this:
<?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"
>
<include layout="#layout/table"/>
</RelativeLayout>
And this is my fragment code of the above layout fragment_test:
public class Fragment_test extends Fragment implements View.OnTouchListener{
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mytable= (LinearLayout) getActivity().findViewById(R.id.mytableid);
typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int i = 0; i < table1.getChildCount(); i++) {
LinearLayout mychild = (LinearLayout) mytable.getChildAt(i);
for (int j = 0; j < mychild.getChildCount(); j++) {
Button b = (Button) child.getChildAt(j);
b.setTypeface(typeface);
b.setOnTouchListener(this);
}
}
}
}
//this is called when a button is touched
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
}
So basically I have several buttons in the table layout I am looping through to setontouchlistener for each one of them.
So my problem is when I switch from protrait to landscape or the opposite the touchlistener of the button does not work anymore and even the typeface doesn't work anymore when changing the layout.
> Edit: this is the activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.container, new Fragment_test(), "mytag").commit();
}
Try calling setRetainInstance(true) after super.onActivityCreated(savedInstanceState);
here is the documentation of setRetainInstance(boolean)
Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
FragmentManager manager = getSupportFragmentManager();
Fragment myFragment = manager.findFragmentByTag("myFragment");
if (myFragment == null) {
myFragment = new ParentFragment();
}
manager.beginTransaction().add(R.id.fragmentHolder, myFragment, "myFragment").commit();
}
}
Fragment:
public class ParentFragment extends Fragment{
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
I am just give you the information.
you can check the Orientataion of device this way and set it layout.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.table_horizontal);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}else if (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.table_vertical);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
}

Android how to action bar action(customize layout) for different tabs?

I am using Actionbar support library. I customized the title and added one button in layout.
Now, I have 2 action tabs with extension of fragment. I want use same button for different functions in different tabs.
I am using Actionbar activity. Below is my code.
Custom action bar layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00FFFFFF" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="1"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/app_green" />
<CheckBox
android:id="#+id/selectAll"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_gravity="top|right"
android:button="#drawable/checkbox"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
My first fragment
public class TestPhotos extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
selectAll();
}
private void selectAll() {
CheckBox b = (CheckBox) getActivity().findViewById(R.id.selectAll);
if (AutoBackupSettings.getInstance().isPhotoBackup()) {
b.setVisibility(View.INVISIBLE);
transferLayout.setVisibility(View.VISIBLE);
} else {
b.setVisibility(View.VISIBLE);
transferLayout.setVisibility(View.GONE);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (stickyAdapter != null) {
if (stickyAdapter.getSelectedCount() == stickyAdapter.list
.size()) {
stickyAdapter.deselectAll();
} else {
stickyAdapter.selectAll();
((PhotosActivity) getActivity())
.setActionBarTitle(getResources().getString(
R.string.all));
}
}
}
});
}
}
My second fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
selectAll();
}
private void selectAll() {
CheckBox b = (CheckBox) getActivity().findViewById(R.id.selectAll);
if (AutoBackupSettings.getInstance().isPhotoBackup()) {
b.setVisibility(View.INVISIBLE);
} else {
b.setVisibility(View.VISIBLE);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (listAdapter != null) {
if (listAdapter.getSelectedCount() == listAdapter.list
.size()) {
listAdapter.deselectAll();
} else {
listAdapter.selectAll();
((PhotosActivity) getActivity())
.setActionBarTitle(getResources().getString(
R.string.all));
}
}
}
});
}
It's working fine in first fragment but I swipe to the second fragment and click on checkbox, it is working for first fragment but not for second one.

Accessing Views inside fragment

I'm having troubles accessing the Views that within my Fragment. In the example below, I can't access the 2nd button that is within the Fragment (e.g., findViewById appears to return NULL and the app crashes when I try b2.setText("test") ), but when I directly add it in the activity_main.xml, it does work.
Here is the code:
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button fragmentButton = (Button)findViewById(R.id.iMainButton);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.iMainInnerLLContainer, new TestFragment());
ft.commit();
final Button b2 = (Button)findViewById(R.id.iTestFragmentInnerButton);
if(b2 == null) { Log.d("MainActivity.java:", "b2 is null"); }
else { Log.d("MainActivity.java:", "b2 is NOT null"); }
fragmentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// do stuff here
}
});
}
}
activity_main.xml
<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:id="#+id/iMainRootLinearLayoutContainer"
android:orientation="vertical"
>
<Button
android:id="#+id/iMainButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Add fragment..."
/>
<LinearLayout
android:id="#+id/iMainInnerLLContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
>
<!-- Fragment goes here, can reference button if it is added here manually -->
</LinearLayout>
</LinearLayout>
TestFragment.java
public class TestFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ltestfragment, container, false);
}
}
ltestfragment.xml
<?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"
android:id="#+id/iTestFragmentOuterLinearLayout"
>
<Button
android:id="#+id/iTestFragmentInnerButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="This is my test fragment button."
/>
</LinearLayout>
I think I'm missing something very basic here and I would appreciate some insight on what that might be.
Thank you in advance!
I think you need to set up a textchangelistener in your fragment.
public class FragmentA extends Fragment {
TextChangeListener listener;
public interface TextChangeListener {
public void onTextChange(CharSequence newText);
}
public void setTextChangeListener(TextChangeListener listener) {
this.listener = listener;
}
Then, in your activity, set up the listener :
public class ActivityAB extends FragmentActivity {
FragmentA fragmentA;
FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ab);
FragmentManager manager = getSupportFragmentManager();
fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA);
fragmentB = (FragmentB) manager.findFragmentById(R.id.fragmentB);
fragmentA.setTextChangeListener(new TextChangeListener() {
#Override
public void onTextChange(CharSequence newText) {
fragmentB.updateTextValue(newText);
}
});
}
}
Implement an interface to listen to the events of a fragment from its activity.
Code in Fragment:-
public class TestFragment extends Fragment
{
public interface OnClickListener
{
public void onButtonClicked(<data type><data>);
}
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listener.onButtonClicked(<<pass some values here>>);
}
});
}
Code in Main:-
MainActivity extends FragmentActivity implements TestFragment.OnClickListener,
{
#Override
public void onButtonClicked(<<receive the pased data here>>) {
//do some stuff here with the received data after the button is clicked
}
}

Adding a button in an activity within fragments with Actionbarsherlock inside the fragment

So I want to have 3 buttons that always appear throughout fragments. I've got an activity with 3 buttons and a fragment layout that contains a fragment with actionbarsherlock inside. The problem is, the buttons in the activity are not clickable and nothing can be executed in the OnClickListener; but the buttons run just fine if I replace the fragment containing actionbarsherlock with a regular fragment without actionbarsherlock inside. I wonder what's wrong.
Here is my code.
activity_main.xml:
<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"
android:paddingBottom="2dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/button1" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/fragment_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:text="mission" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:text="feed" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/fragment_content"
android:text="Profile" />
</RelativeLayout>
MyActivity.java:
public class MyActivity extends SherlockFragmentActivity {
/**
* Called when the activity is first created.
*/
Fragment frg;
ActionBarFragment b;
Button btnmission;
Button btnfeed;
Button btnprofile;
boolean small;
static int previousItem;
int tabname;
private Fragment mVisible = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previousItem=1;
btnmission = (Button) findViewById(R.id.button1);
btnfeed = (Button) findViewById(R.id.button2);
btnprofile = (Button) findViewById(R.id.button3);
btnmission.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("clicked", "button");
if(previousItem!=1){
Intent intent=new Intent(getBaseContext(),MyActivity.class);
startActivity(intent);
}
previousItem=1;
}
});
btnfeed.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(previousItem!=2){
Intent intent=new Intent(getBaseContext(),MissionFragment.class);
intent.putExtra("class", "Feed");
startActivity(intent);
}
previousItem=2;
}
});
btnprofile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
private void setupFragments() {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
frg = (ActionBarFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_content);
if (frg == null) {
frg = new ActionBarFragment();
ft.add(R.id.fragment_content, frg);
}
ft.hide(frg);
ft.commit();
}
private void showFragment(Fragment fragmentIn) {
if (fragmentIn == null) return;
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (mVisible != null) ft.hide(mVisible);
ft.show(fragmentIn).commit();
mVisible = fragmentIn;
}
It adds a fragment to the activity and actionbar inside the fragment.
ActionBarFragment.java:
public class ActionBarFragment extends SherlockFragment {
int tabname;
#Override
public void onStart()
{
// TODO Auto-generated method stub
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.empty_view, container, false);
// Getting an instance of action bar
ActionBar actionBar = this.getSherlockActivity().getSupportActionBar();
// Enabling Tab Navigation mode for this action bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Enabling Title
actionBar.setDisplayShowTitleEnabled(true);
// Creating Android Tab
Tab tab1 = actionBar.newTab()
.setText("Nova Missoes")
.setTabListener(new CustomTabListener<ListMission>(this.getSherlockActivity(), "mission list", ListMission.class));
// Adding Android Tab to action bar
actionBar.addTab(tab1);
// Creating Apple Tab
Tab tab2 = actionBar.newTab()
.setText("Missoes Concluidas")
.setTabListener(new CustomTabListener<MissionAccomplished>(this.getSherlockActivity(), "mission accomplished", MissionAccomplished.class));
// Adding Apple Tab to action bar
actionBar.addTab(tab2);
Intent in=getSherlockActivity().getIntent();
tabname=in.getIntExtra("tabname", 0);
Log.i("intent", Integer.toString(tabname));
if(tabname==2){
actionBar.selectTab(tab2);
}
// Orientation Change Occurred
if(savedInstanceState!=null){
int currentTabIndex = savedInstanceState.getInt("tab_index");
actionBar.setSelectedNavigationItem(currentTabIndex);
}
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
int currentTabIndex = getSherlockActivity().getSupportActionBar().getSelectedNavigationIndex();
outState.putInt("tab_index", currentTabIndex);
super.onSaveInstanceState(outState);
}
}
No problem with displaying the buttons and the tabs, it's just that the OnClickListener is not called when the program runs.

Categories

Resources