My goal here is to change an Image from an ImageButton(ibChamp).
package com.example.custombuilds;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;z
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class Champions extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.champions);
ImageButton ibAnnie = (ImageButton) findViewById(R.id.ibAnnie);
ibAnnie.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Check this for errors
RelativeLayout test = (RelativeLayout) findViewById(R.id.layoutChampions);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.create_build_page, null);
test.addView(view);
ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
img.setImageResource(R.drawable.ic_launcher);
try {
Intent open = new Intent("android.intent.action.CREATE");
startActivity(open);
} catch (Exception e) {
}
}
});
}
}
Note that the ImageButton ibChamp is from the xml layout create_build_page, and not the xml champions.
This code runs without crashing, but the Image from the Imagebutton ibChamp does not change, which is what I am trying to do. I will be happy to provide any other additional information.
You are inflating "ibChamp" in onClick. That creates a new ImageButton. You will not see it until you use "addView" from the parent.
You can add your XML, but you need to get a reference to an existing button in Activity in order to change it. Or else add the new button and remove an old one...
In other words, change this:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.create_build_page, null);
ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
to this:
ImageButton img = (ImageButton)findViewById(R.id.ibChamp);
And it will probably do what you want.
you need to call addView() for this inflated view
View view = layoutInflater.inflate(R.layout.create_build_page, null);
Related
I am trying to change icon image according to the item data . when pressing the icon, it should switch to other icon and change the item data. everything is going right but when i scroll up or down the new icon image change its place to some other items because i am using list view with adapter. how can i keep the new icons in the pressed items without mixing with other items.
package com.example.sairamkrishna.handymade;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HandAdapter extends ArrayAdapter<HandClass> {
private int myColor;
public HandAdapter(Context context, ArrayList<HandClass> objects, int my_Color) {
super(context, 0, objects);
myColor = my_Color;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View myView = convertView;
final HandClass myData = getItem(position);
if (myView == null) {
myView = LayoutInflater.from(getContext()).inflate(
R.layout.label_item, parent, false);
}
ImageView aImage = (ImageView) myView.findViewById(R.id.itemImage);
aImage.setImageResource(myData.getClsImage());
TextView aName = (TextView) myView.findViewById(R.id.itemName);
aName.setText(myData.getClsName());
FrameLayout aColor = (FrameLayout) myView.findViewById(R.id.itemColor);
aColor.setBackgroundColor(myColor);
final ImageView aAddToBasket = (ImageView) myView.findViewById(R.id.itemAddToBasket);
aAddToBasket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Boolean aClsToBasket = (Boolean) myData.getClsToBasket();
if (aClsToBasket) {
aAddToBasket.setImageResource(R.drawable.ic_add_circle);
myData.setClsToBasket(false);
Toast.makeText(getContext(), "Remove from basket"+ position, Toast.LENGTH_SHORT).show();
} else {
// if (!aClsToBasket) {
aAddToBasket.setImageResource(R.drawable.ic_remove_circle);
myData.setClsToBasket(true);
Toast.makeText(getContext(), "Add to basket"+ position, Toast.LENGTH_SHORT).show();
}
}
});
ImageView aAddToFavorite = (ImageView) myView.findViewById(R.id.itemAddToFavorite);
aAddToFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Favorite - List item was clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
return myView;
}
}
A fundamental concept of ListView and RecyclerView is that you need to "update" the value (in this case, the image) for each portion of the row every time getView() or onBindViewHolder() is called.
For example, every time getView() is called, you're always updating the (text) value of TextView aName. That is, there is always a call to aName.setText().
Right now, the only time you call aAddToBasket.setImageResource() is inside an OnClickListener. Of course, it makes sense to do it here, but you must also update the image outside of the listener.
Add this code right after your ImageView aAddToBasket line:
if ((Boolean) myData.getClsToBasket()) {
aAddToBasket.setImageResource(R.drawable.ic_remove_circle);
} else {
aAddToBasket.setImageResource(R.drawable.ic_add_circle);
}
Add this line after icon change.
adapter.notifyDataSetChanged();
I want to make a newsletter app with the feature to make posts yourself.
I'm trying to makr a code for a button and I am stuck at the one moment. I don't know how to set a position for a new textView in the new cardView.
Here is a piece of code from MainActivity.java
package com.example.rame956.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScrollView scrollView = new ScrollView(this);
}
//<...>
public void CreateNewPost(View view){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
CardView card = new CardView(this);
TextView text = new TextView(this);
ImageView image = new ImageView(this);
}
}
Sorry if it's a dumb qustion. I'm new in android developing.
For starters, I'd assume you would at least have a button inside your MainActivity which will trigger the process of creating a cardview. Therefore, to answer your question, I'll create a brand new card view programmatically from scratch. Take the elements which you need out of it i.e. textview, buttons and so on.
// Wiring in my 2 main aspects relativeLayout + Button
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
button = (Button) findViewById(R.id.btn);
//my trigger but in your case, it can be anything
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CardView card = new CardView(mContext);
// Set the CardView layoutParams
LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
card.setLayoutParams(layoutParams );
// Setting different attributes
card.setRadius(9);
card.setContentPadding(15, 15, 15, 15);
card.setCardBackgroundColor(Color.parseColor("#FFC6D6C3"));
card.setMaxCardElevation(15);
card.setCardElevation(9);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(mContext);
tv.setLayoutParams(layoutParams );
tv.setText("My CardView");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.RED);
// Put the TextView inside CardView
card.addView(tv);
// Finally, add the CardView in root layout
relativeLayout.addView(card);
}
});
One thing to note here is the relativeLayout at the end of the function. You will need to have a parent layout in which you'll be placing your cardview. And of course, the attributes can be modified to your needs i.e. settext, backgroundcolour and so on.
If you simply want to insert a TextView to a pre-existing CardView in your xml. It'll be the same concept.
card = (CardView)findViewById(R.id.cardView);
//generate your textview as above....
card.addView(textView);
This question already has answers here:
I'm having problems with running the code on my device [duplicate]
(3 answers)
Closed 4 years ago.
I am currently getting these errors when running my code on a device
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 9401
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:46)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
now based on what I see here are the libraries for the code its stating in the error. Please help im a beginner
Events.java
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.app.FragmentManager;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events,
container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
Intent intent = new Intent(view.getContext(),
AddEvent.class);
Uri currentVehicleUri =
ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton)
getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),
AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity
context
EventContract.EventEntry.CONTENT_URI, // Provider
content URI to query
projection, // Columns to include in the
resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Fragment Java(it says im getting an error around here:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
if (mHost != null) {
writer.print(prefix); writer.print("mHost=");
writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
writer.println(mParentFragment);
In conclusion I'm trying to run the app but everytime I go into a certain section, in this case being Events.java being nav_events.xml layout, I keep getting the error and don't know how to fix it
Your error is found on line 46 of your Events.java file.
You're inflating a view and declaring it a ListView in Java (on line 46) when it seems to be a LinearLayout in your XML file.
Also right after that you're using getView(). You can only use that function correctly after onCreateView() has returned a View, definitely not within it.
EDIT after comment:
You haven't returned the View yet as you can't execute any code after a return statement.
Now without your layout file I can only speculate but probably replace
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
with
View rootView = (LinearLayout) inflater.inflate(R.layout.nav_events, container, false);
Then replace all occurrences of getView() in that code block with rootView.
And at the very end
return rootView;
package com.example.firstapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
import static com.example.firstapplication.MainActivity.EXTRA_MESSAGE;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
if (EXTRA_MESSAGE.equals ("h")) {
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}else {
TextView textView = new TextView(this);
textView.setTextSize(4);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
}
if i type in h on my thing the output should be h in size 40 font and it should work only for h, but when is type in h or anything else it comes out in size 4, help, what do i do
I think instead of EXTRA_MESSAGE, do you want to check with message string?
Else you can use the debug mode in Android Studio to know what variables contains.
I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary