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);
Edit: I am new to Android, I don't want to use databases or etc to store the credentials, I just want to make the if statement to work...
So, I am trying to make a simple login system for an app. After I
press login, the toast returns the false message, but the strings are true, what I am doing wrong when I am trying to verify those? (if statement)
package com.example.reevo.a02activities07;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import static android.R.attr.button;
import static android.R.attr.onClick;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
TextView textViewUsername, textViewPassword;
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewPassword = (TextView) findViewById(R.id.userInput);
textViewUsername = (TextView) findViewById(R.id.passwordInput);
loginButton = (Button) findViewById(R.id.buttonLogin);
}
public void onClick(View view){
if (textViewUsername.getText().toString().equals("admin") && textViewPassword.getText().toString().equals("pass")){
Toast.makeText(getApplicationContext(), "Succesfull!", Toast.LENGTH_SHORT).show();
} else Toast.makeText(getApplicationContext(), "Wrong credentials!", Toast.LENGTH_SHORT).show();
}
}
The textViewPassword is pointing to R.id.userInput and textViewUsername to R.id.passwordInput. You should change it
there is mistake in your binding controll check it
use this
textViewPassword = (TextView) findViewById(R.id.passwordInput);
textViewUsername = (TextView) findViewById(R.id.userInput);
insted of this
textViewPassword = (TextView) findViewById(R.id.userInput);
textViewUsername = (TextView) findViewById(R.id.passwordInput);
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
I want to run the app by using Java code instead of XML files.
The app is not working on my phone/emulator and crashing every time.
The code looks like this:
package com.nikhil.relativelayoutjavacode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
RelativeLayout main;
EditText userNameValue, passwordValue;
TextView message, userName, password;
LayoutParams messageDimensions;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessageTextView();
main.addView(message, messageDimensions);
setContentView(main);
}
private void init() {
// TODO Auto-generated method stub
main = new RelativeLayout(this);
LayoutParams mainDimensions = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
main.setLayoutParams(mainDimensions);
userNameValue = new EditText(this);
passwordValue = new EditText(this);
message = new TextView(this);
userName = new TextView(this);
password = new TextView(this);
login = new Button(this);
}
private void createMessageTextView() {
LayoutParams messageDimensions = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
messageDimensions.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
message.setText("Please Login First");
message.setLayoutParams(messageDimensions);
}
}
Here:
main.addView(message, messageDimensions);
messageDimensions is null because creating new object of LayoutParams with name messageDimensions in createMessageTextView() method instead of using messageDimensions object which is declared at class level.
So, use :
messageDimensions = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
messageDimensions.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
in createMessageTextView() method.
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);