Android Imagebutton fragment - java

Hey guys so i'm trying to get my imagebutton to work within my fragment. The code works fine with a Activity but I cannot get it to work within the fragment. What do I need to change? Errors keep occurring within the configureImage method, Thanks guys.
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*
*/
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_a);
configureImageButton();
}
private void configureImageButton() {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(FragmentA.this, "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}

Your fragment implementations is wrong. Do this way.
public class FragmentA extends Fragment {
private View v;
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_a,container, false);
configureImageButton();
return v;
}
private void configureImageButton() {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) v.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}
}

public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_a, container, false);
configureImageButton(view);
return view;
}
private void configureImageButton(View view) {
// TODO Auto-generated method stub
ImageButton btn = (ImageButton) view.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
}
}

use this this will work for you, and follow this for fragment.
public class FragmentA extends Fragment {
ViewGroup rootViewA;
ImageButton btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootViewA = (ViewGroup) inflater.inflate(
R.layout.fragment_a, container, false);
btn = (ImageButton ) rootViewA
.findViewById(R.id.imageButton1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
}
});
return rootViewA;
}
}

Related

fragment won't hide

I have a navbar which is supposed to be hidden when a button is pressed, but nothing happens.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mavisTxt;
private Button testBtn;
private Fragment navigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariables();
}
private void initVariables() {
navigationBar = new HeaderNav();
mavisTxt = (TextView)findViewById(R.id.mavisTxt);
testBtn = (Button)findViewById(R.id.testBtn);
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.hide(navigationBar)
.commit();
mavisTxt.setText("navbar is hidden");
}
});
}
}
Here is the java file for the fragment
public class HeaderNav extends Fragment {
private static Button homeBtn, optionsBtn, connectionBtn, micBtn, aboutBtn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.navbar, container, false);
homeBtn = (Button)view.findViewById(R.id.homeBtn);
optionsBtn = (Button)view.findViewById(R.id.optionsBtn);
connectionBtn = (Button)view.findViewById(R.id.micBtn);
micBtn = (Button)view.findViewById(R.id.homeBtn);
aboutBtn = (Button)view.findViewById(R.id.aboutBtn);
return view;
}
}
and the fragment tag in the main_activity xml :
<fragment
android:id="#+id/navigationBar"
android:name="com.example.egi.mavisme.HeaderNav"
android:layout_width="fill_parent"
android:layout_height="60dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout="#layout/navbar" />
what am I doing wrong? none of the solutions here in SO works for me. Someone help me.
EDIT:
I have edited my code and now it hides. I have another issue when adding a custom animation, I am getting a
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.startViewTransition(android.view.View)' on a null object reference
Here is my code now :
public class MainActivity extends AppCompatActivity {
private TextView mavisTxt;
private Button testBtn;
private HeaderNav navigationBar;
private FragmentManager fm;
private FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariables();
}
private void initVariables() {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
navigationBar = (HeaderNav)fm.findFragmentById(R.id.navigationBar);
mavisTxt = (TextView)findViewById(R.id.mavisTxt);
testBtn = (Button)findViewById(R.id.testBtn);
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(navigationBar)
.commit();
if(navigationBar.isHidden()) {mavisTxt.setText("navbar is hidden");}
}
});
}
}
Here are some things to note-
Use the ActionBar/ToolBar, this isn't iOS
You have to add a fragment first
You are using the show call instead of hiding it
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.**show**(navigationBar)
.commit();
mavisTxt.setText("navbar is hidden");
}
});

I have a code break in this fragment but I can't solve it.. It showing that I have null reference ob set text but when I debug I see data

## fragment 1
I am geting null reference on setText on TextView control but I can't find a reason why...
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.OpstinaVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
public class PosiljaocFragment extends Fragment {
public static final String NEKI_KLJUC = "nekiKljuc";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView viewImePosiljaoca;
private TextView adresaPosiljaoca;
private PosiljkaVM posiljkaVM = new PosiljkaVM();
private OpstinaVM opstina;
public PosiljaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PosiljaocFragment newInstance(PosiljkaVM posiljka) {
PosiljaocFragment fragment = new PosiljaocFragment();
Bundle args = new Bundle();
args.putSerializable(NEKI_KLJUC, posiljka);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
posiljkaVM = (PosiljkaVM) getArguments().getSerializable(NEKI_KLJUC);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_posiljaoc, container, false);
viewImePosiljaoca = (TextView) view.findViewById(R.id.viewImePosiljaoca);
adresaPosiljaoca = (TextView) view.findViewById(R.id.viewAdresaPosiljaoca);
final Button btnPromjeniPosiljaoca = (Button) view.findViewById(R.id.btnPromjeniPosiljaoca);
Button btnDalje = (Button) view.findViewById(R.id.btnDalje);
if (posiljkaVM.posljiaoc != null){
viewImePosiljaoca.setText(posiljkaVM.posljiaoc.getIme() + " " + posiljkaVM.posljiaoc.getPrezime());
adresaPosiljaoca.setText(posiljkaVM.posljiaoc.getAdresa() + " - " + posiljkaVM.posljiaoc.getOpstinaVM().getNaziv());
}
btnDalje.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDaljeClick();
}
});
btnPromjeniPosiljaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPosiljaocaClick();
}
});
return view;
}
private void btnDaljeClick() {
if (posiljkaVM.primaoc == null){
posiljkaVM.primaoc = new KorisnikVM("", "", new OpstinaVM(0,"",""), "");
}
if (posiljkaVM.posljiaoc == null){
posiljkaVM.posljiaoc = new KorisnikVM(posiljkaVM.posljiaoc.getIme(), posiljkaVM.posljiaoc.getPrezime(), opstina, "");
}
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(posiljkaVM));
}
private void btnPromjeniPosiljaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
posiljkaVM.posljiaoc = result;
viewImePosiljaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPosiljaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv());
posiljkaVM.posljiaoc.setIme(result.getIme());
posiljkaVM.posljiaoc.setPrezime(result.getPrezime());
posiljkaVM.posljiaoc.setOpstinaVM(result.getOpstinaVM());
posiljkaVM.posljiaoc.setAdresa(result.getAdresa());
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
### dialog fragment
package ba.fit.app.hci_odbrana.fragmenti;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.Storage;
public class KorisniciFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private MyRunnable<KorisnikVM> callback;
private String mParam2;
private EditText txtImePrezime;
private ListView listKorisnici;
private TextView linija1;
private TextView linija2;
private List<KorisnikVM> podaci;
public KorisniciFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static KorisniciFragment newInstance(MyRunnable<KorisnikVM> myCallback) {
KorisniciFragment fragment = new KorisniciFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, myCallback);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
callback = (MyRunnable<KorisnikVM>) getArguments().getSerializable(ARG_PARAM1);
}
setStyle(STYLE_NORMAL, R.style.MojDijalog);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_korisnici, container, false);
txtImePrezime = (EditText) view.findViewById(R.id.txtImePrezime);
listKorisnici = (ListView) view.findViewById(R.id.listKorisnici);
Button btnTrazi = (Button) view.findViewById(R.id.btnTrazi);
popuniPodatke("");
btnTrazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnTraziClick();
}
});
listKorisnici.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
KorisnikVM x = podaci.get(position);
getDialog().dismiss();
callback.run(x);
}
});
return view;
}
private void btnTraziClick() {
popuniPodatke(txtImePrezime.getText().toString());
}
private void popuniPodatke(String name) {
podaci = Storage.getKorisniciByName(name);
listKorisnici.setAdapter(new BaseAdapter() {
#Override
public int getCount() {
return podaci.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
KorisnikVM x = podaci.get(position);
if( view == null)
{
final LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.stavka_korisnici, viewGroup, false);
}
linija1 = (TextView) view.findViewById(R.id.linija1);
linija2 = (TextView) view.findViewById(R.id.linija2);
linija1.setText(x.getIme() + " " + x.getPrezime());
linija2.setText(x.getOpstinaVM().getNaziv() + " - " + x.getAdresa());
return view;
}
});
}
}
## Fragment 2
Here everything works fine and it's very similar to first one.
package ba.fit.app.hci_odbrana.fragmenti;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
/**
* A simple {#link Fragment} subclass.
* Use the {#link PrimaocFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PrimaocFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private TextView viewImePrimaoca;
private TextView adresaPrimaoca;
public PrimaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PrimaocFragment newInstance(PosiljkaVM param1) {
PrimaocFragment fragment = new PrimaocFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_primaoc, container, false);
viewImePrimaoca = (TextView) view.findViewById(R.id.viewImePrimaoca);
adresaPrimaoca = (TextView) view.findViewById(R.id.viewAdresaPrimaoca);
final Button btnPromjeniPrimaoca = (Button) view.findViewById(R.id.btnPromjeniPrimaoca);
final Button btnNazad = (Button) view.findViewById(R.id.btnNazad);
final Button btnDalje2 = (Button) view.findViewById(R.id.btnDalje2);
if (getArguments() != null){
viewImePrimaoca.setText(mParam1.primaoc.getIme() + " " + mParam1.primaoc.getPrezime());
adresaPrimaoca.setText(mParam1.primaoc.getAdresa() + " - " + mParam1.primaoc.getOpstinaVM().getNaziv());
}
btnDalje2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDalje2Click();
}
});
btnNazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazadClick();
}
});
btnPromjeniPrimaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPrimaocaClick();
}
});
return view;
}
private void btnNazadClick() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
}
private void btnDalje2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PaketFragment.newInstance(mParam1));
}
private void btnPromjeniPrimaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
mParam1.primaoc = result;
viewImePrimaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPrimaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv()); //here is where I get that null reference
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
## package fragment
This is for showing some details on package that is been sent when you chose sender and receiver
public class PaketFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private EditText txtMasa;
private EditText txtNapomena;
public PaketFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PaketFragment newInstance(PosiljkaVM param1) {
PaketFragment fragment = new PaketFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_paket, container, false);
txtMasa = (EditText) view.findViewById(R.id.txtMasa);
txtNapomena = (EditText) view.findViewById(R.id.txtNapomena);
final Button btnZavrsi = (Button) view.findViewById(R.id.btnZavrsi);
final Button btnNazad2 = (Button) view.findViewById(R.id.btnNazad2);
btnNazad2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazad2Click();
}
});
btnZavrsi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnZavrsiClick();
}
});
return view;
}
private void btnZavrsiClick() {
try {
mParam1.masa = Float.parseFloat(txtMasa.getText().toString());
mParam1.napomena = txtNapomena.getText().toString();
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
Toast.makeText(getActivity(), "Uspješno spremljena pošiljka!", Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getActivity(), "Greška: " + e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private void btnNazad2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(mParam1));
}
}
That's it.. hope someone can help me. Have a pleasant day.

App is crashed after adding switch case in gridview

I got the problem when I tried to add switch case in custom page adapter. I can toast if one item of gridview is clicked. But when I tried to add new activity with onClick, app is crashed. I want to show new activity if gridview item is clicked. I've searched and studied regarding this problem, but I can't find solution.I think my problem is related to switch case. I am learning android. Please help me.
CustomAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] osNameList, int[] osImages) {
// TODO Auto-generated constructor stub
result=osNameList;
context=mainActivity;
imageId=osImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView os_text;
ImageView os_img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.sample_gridlayout, null);
holder.os_text =(TextView) rowView.findViewById(R.id.os_texts);
holder.os_img =(ImageView) rowView.findViewById(R.id.os_images);
holder.os_text.setText(result[position]);
holder.os_img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch(position){
case 0:
Intent a = new Intent(v.getContext(), FirstActivity.class);
v.getContext().startActivity(a);
break;
case 1:
Intent b = new Intent(v.getContext(), DefaultActivity.class);
v.getContext().startActivity(b);
break;
}
} });
return rowView;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
public class MainActivity extends Activity {
GridView gridview;
public static String[] osNameList = {
"Android",
"iOS",
"Linux",
};
public static int[] osImages = {
R.drawable.alpha,
R.drawable.beta,
R.drawable.cupcake,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.customgrid);
gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
}
}
This is not the way to set OnItemClick Listener. If you want to set click on whole item you should use OnItemClickListener. Remove the OnClickListener from getView() and use OnItemClickListener as follows.
GridView gridview = (GridView) findViewById(R.id.customgrid);
gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent a = new Intent(v.getContext(), FirstActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(v.getContext(), DefaultActivity.class);
startActivity(b);
break;
default:
break;
}
} });
NOTE:- There is no need of switch inside OnClickListener which is inside getView() because its only going to call for one position at a time.

Android Studio | Button onClick in a NavigationDrawer Fragment

I'm struggling with these errors for a few days already, I tried googling it, but unfortunately I can't find any fixes for this.
I'm still a beginner in Java for Android.
So I got a NavigationDrawer with a Fragment, in that fragment i want to put a button which is clickable, but somehow it just doesn't recognize the button and some things while I've got it in my layout.
This is my code:
package nl.c99.c99nlapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Souf on 21-9-2015.
*/
public class First_Fragment extends Fragment {
View MyView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyView = inflater.inflate(R.layout.first_layout, container, false);
return MyView;
View rootView = inflater.inflate(R.layout.first_layout, container, false);
Button c = (Button) rootView.findViewById(R.id.button2);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onClick(v);//THIS IS THE METHOD YOU WROTE ON THE ATTACHED CODE!!
}
});
}
}
Screenshot of my project:
First_Fragment Class
http://i.stack.imgur.com/5W2uG.png
Layout of first_fragment:
http://i.imgur.com/ndVmcX2.png
I'm getting the following errors:
Cannot resolve symbol 'OnClickListener' (new OnClickListener)
Method does not override method from its superclass (#Override)
Parameter 'v' is never used. (View v)
Method OnClick is never used (public void onClick)
Cannot resolve symbol 'OnClickListener' (new OnClickListener)
Add this in your imports : import android.view.View.OnClickListener;
You just have to choose one of your views, since you have 2 I don't know why rootView and MyView then your onClickListener() should be :
Button c = (Button) MyView.findViewById(R.id.button2);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your stuff here
}
});
Parameter 'v' is never used. (View v)
Just remove this onClick(v)
Your coude should work if you do this :
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyView = inflater.inflate(R.layout.first_layout, container, false);
Button c = (Button) MyView.findViewById(R.id.button2);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Stuff there
}
});
return MyView;
}
All fo your code
package nl.c99.c99nlapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
/**
* Created by Souf on 21-9-2015.
*/
public class First_Fragment extends Fragment {
View MyView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyView = inflater.inflate(R.layout.first_layout, container, false);
Button c = (Button) MyView.findViewById(R.id.button2);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Stuff there
}
});
return MyView;
}
}
You must return your rootView at the end of your code, because return means "end that method", so it won't continue the code below it in the same method.
Replace your code with this one:
package nl.c99.c99nlapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class First_Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first_layout, container, false);
Button c = (Button) rootView.findViewById(R.id.button2);
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Write your code here.
}
});
return rootView;
}
}

Button does nothing, but why?

I am basically only trying to get R.id.button1 to open up Google in a web browser, not sure whats wrong!
No errors, it just does nothing when pressing the button, I am using the emulator.
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
}
public void onClick(View v)
{
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
It seems to me your button is in your fragment layout (right?)
then you should handle your button's events in your fragment, not in the activity!
Your onCreate() method should be like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener{
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
});
}
The problem is here :
btn.setOnClickListener((OnClickListener) this);
replace it with :
btn.setOnClickListener(this);
And implement View.OnClickListner in order to get the onClick method
public class MainActivity extends ActionBarActivity implements View.OnClickListner {
/*
some code here
*/
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
}
You can also do it like this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
});
Implement OnClickListner
public class MainActivity extends ActionBarActivity implements OnClickListner {
Button btn;
Define the listener to your button1.
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
use a switch in onClick() method to handle several views:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
break;
default:
//code..
break;
};
}
other way to set the listener to your button:
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener{
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}

Categories